How to set timeout for http.Get() requests in Golang?

后端 未结 7 1395
刺人心
刺人心 2020-12-22 16:15

I\'m making a URL fetcher in Go and have a list of URLs to fetch. I send http.Get() requests to each URL and obtain their response.

resp,fetch_e         


        
7条回答
  •  粉色の甜心
    2020-12-22 16:45

    A quick and dirty way:

    http.DefaultTransport.(*http.Transport).ResponseHeaderTimeout = time.Second * 45
    

    This is mutating global state w/o any coordination. Yet it might be possibly okay for your url fetcher. Otherwise create a private instance of http.RoundTripper:

    var myTransport http.RoundTripper = &http.Transport{
            Proxy:                 http.ProxyFromEnvironment,
            ResponseHeaderTimeout: time.Second * 45,
    }
    
    var myClient = &http.Client{Transport: myTransport}
    
    resp, err := myClient.Get(url)
    ...
    

    Nothing above was tested.

提交回复
热议问题