Context in HTTP and Database Calls
Propagating context through the call chain
HTTP client with context
Pass a context to an outgoing HTTP request using req.WithContext(ctx). The request is cancelled if the context is cancelled before the response arrives.
req, _ := http.NewRequestWithContext(ctx, "GET", url, nil)
resp, err := http.DefaultClient.Do(req)
if err != nil {
if errors.Is(err, context.DeadlineExceeded) {
// timeout
}
}http.NewRequestWithContext
Prefer http.NewRequestWithContext (Go 1.13+) over creating a request then calling WithContext — it is cleaner and avoids an intermediate allocation.
All lessons in this course
- Why context.Context Exists
- WithCancel and WithTimeout
- WithDeadline and WithValue
- Context in HTTP and Database Calls