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
That's done the trick for me.
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:
You may use https://github.com/franela/goreq which handles timeouts in a fashion and simple way.
A quick and dirty way:
This is mutating global state w/o any coordination. Yet it might be possibly okay for your url fetcher. Otherwise create a private instance of
http.RoundTripper
:Nothing above was tested.
If you want to do it per request, err handling ignored for brevity:
To add to Volker's answer, if you would also like to set the read/write timeout in addition to the connect timeout you can do something like the following
This code is tested and is working in production. The full gist with tests is available here https://gist.github.com/dmichael/5710968
Be aware that you will need to create a new client for each request because of the
conn.SetDeadline
which references a point in the future fromtime.Now()