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

后端 未结 7 1388
刺人心
刺人心 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:59

    You need to set up your own Client with your own Transport which uses a custom Dial function which wraps around DialTimeout.

    Something like (completely untested) this:

    var timeout = time.Duration(2 * time.Second)
    
    func dialTimeout(network, addr string) (net.Conn, error) {
        return net.DialTimeout(network, addr, timeout)
    }
    
    func main() {
        transport := http.Transport{
            Dial: dialTimeout,
        }
    
        client := http.Client{
            Transport: &transport,
        }
    
        resp, err := client.Get("http://some.url")
    }
    

提交回复
热议问题