TIL: context cancellation in Go
- go
- concurrency
Cancellation only works when every layer accepts and forwards the same context.Context. Passing it into database calls, HTTP requests, and worker functions lets a timeout or client disconnect stop work that no longer has a caller waiting for it.
The receiving function should check ctx.Done() at blocking boundaries and return ctx.Err() instead of inventing a separate sentinel error. That keeps upstream logging and retry behavior tied to the original cancellation reason.
func fetchProfile(ctx context.Context, client *http.Client, url string) (*http.Response, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return nil, err
}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
return resp, nil
}