douzuanze0486 2013-06-03 11:06
浏览 688
已采纳

如何在Golang中为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)

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?

  • 写回答

7条回答 默认 最新

  • duanniu4106 2014-08-16 22:10
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(6条)

报告相同问题?