package main import ( "context" "time" "net/http" "fmt" "io/ioutil" ) type Result struct { r *http.Response err error } func process() { ctx,cancel := context.WithTimeout(context.Background(), 2*time.Second) defer cancel() tr := &http.Transport{} client := &http.Client{Transport:tr} c := make(chan Result, 1) req, err := http.NewRequest("GET", "http://google.com", nil) if err != nil{ fmt.Println("http request filed, err:", err) return } go func() { resp, err := client.Do(req) pack := Result{r:resp, err:err} c <- pack }() select { case <- ctx.Done()://内部也是一个管道,如果这个管道能够读到数据,说明已经超时了 tr.CancelRequest(req)//取消正在请求的http请求 res := <-c fmt.Println("timeout!", res.err) case res := <-c: defer res.r.Body.Close() out, _ := ioutil.ReadAll(res.r.Body) fmt.Printf("server response:%s", out) } return } func main() { process() }
执行结果
timeout! Get http://google.com: net/http: request canceled while waiting for connection