本文介绍了如何在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 有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.

这篇关于如何在Golang中设置http.Get()请求的超时时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-27 16:07