如何在Golang中设置http.Get()请求的超时时间?

问题描述:

我在Go中制作一个URL获取器,并拥有要获取的URL列表。我向每个URL发送 http.Get()请求并获得他们的回复。

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_err := http.Get(url)

如何设置自定义超时为每个获取请求? (默认时间非常长,这使得我的fetcher真的很慢。)我希望我的fetcher有大约40-45秒的超时时间,之后它应该返回请求超时并转到下一个URL。

How can I set a custom timeout for each Get request? (The default time is very long and that makes my fetcher really slow.) I want my fetcher to have a timeout of around 40-45 seconds after which it should return "request timed out" and move on to the next URL.

我该如何实现这一目标?

How can I achieve this?

显然,在Go 1.3 http.Client 有Timeout字段

Apparently in Go 1.3 http.Client has Timeout field

timeout := time.Duration(5 * time.Second)
client := http.Client{
    Timeout: timeout,
}
client.Get(url)

这对我来说已经完成了。

That's done the trick for me.