Context with a timeout in Go

Go

Cancels the request and everything downstream of it after two seconds. The defer is not optional.

ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()

req, _ := http.NewRequestWithContext(ctx, "GET", url, nil)
resp, err := http.DefaultClient.Do(req)

More in Systems

Random picks