如何在 Golang 中为 http.Get() 请求设置超时? [英] How to set timeout for http.Get() requests in Golang?

查看:32
本文介绍了如何在 Golang 中为 http.Get() 请求设置超时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用 Go 制作一个 URL 获取器,并有一个要获取的 URL 列表.我向每个 URL 发送 http.Get() 请求并获得它们的响应.

resp,fetch_err := http.Get(url)

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

我怎样才能做到这一点?

解决方案

显然在 Go 1.3 http.Client 有超时字段

client := http.Client{超时:5 * time.Second,}客户端获取(网址)

这对我来说已经成功了.

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)

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?

解决方案

Apparently in Go 1.3 http.Client has Timeout field

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

That's done the trick for me.

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆