go语言context超时控制代码示例

package main

import (
	"context"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"time"
)
//存储响应结果
type Result struct {
	resp *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 {
		log.Println("请求谷歌失败:",err)
		return
	}
	go func(){
		fmt.Println("aaaaaaaa")
		resp, err := client.Do(req)
		fmt.Println("bbbbbbbb")
		pack := Result{resp:resp, err:err}
		c <-pack
	}()
	select {
	case <-ctx.Done(): //2s超时后
		tr.CancelRequest(req) //取消请求resp, err := client.Do(req),不再继续请求谷歌,
		<-c
		log.Println("Timeout")
	case res := <-c:
		defer res.resp.Body.Close()
		out,_:=ioutil.ReadAll(res.resp.Body)
		fmt.Printf("Server Response:%s",out)
	}


}

func main(){
	process()
}

 

你可能感兴趣的:(go)