Essential Go HTTP Client  Suggest an edit

Timeout requests with a context

Since Go 1.7 you can timeout individual HTTP request using context.Context.

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)
}

ctx, _ := context.WithTimeout(context.TODO(), time.Millisecond*100)
req = req.WithContext(ctx)

resp, err := http.DefaultClient.Do(req.WithContext(ctx))
if err != nil {
	log.Fatalf("http.DefaultClient.Do() failed with:\n'%s'\n", err)
}
defer resp.Body.Close()
2018/10/18 02:24:52 http.DefaultClient.Do() failed with:
'Get https://httpbin.org/delay/3: context deadline exceeded'
exit status 1

  ↑ ↓ to navigate     ↵ to select     Esc to close