Timeout requests with a context
suggest changeSince Go 1.7 you can time out an individual HTTP request with context.Context.
// httpbin.org is a service for testing HTTP client
// this URL waits 3 seconds before returning a response
uri := "https://httpbin.org/delay/3"
req, err := http.NewRequest("GET", uri, nil)
if err != nil {
log.Fatalf("http.NewRequest() failed with '%s'\n", err)
}
// create a context indicating a 100 ms timeout
// Always call cancel. It releases the timer if Do returns early.
ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond*100)
defer cancel()
// get a new request based on original request but with the context
req = req.WithContext(ctx)
resp, err := http.DefaultClient.Do(req)
if err != nil {
// the request should timeout because we want to wait max 100 ms
// but the server doesn't return response for 3 seconds
log.Fatalf("http.DefaultClient.Do() failed with:\n'%s'\n", err)
}
defer resp.Body.Close()
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents