Context in Go
From the Go cheat sheet · Context · verified Jul 2026
Context
Cancellation, timeouts, and passing request-scoped data
go
// With cancel
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
// With timeout
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
// Check if done
select {
case <-ctx.Done():
fmt.Println(ctx.Err()) // context canceled
}📌 Always pass context as the first function parameter
🎯 Always defer cancel() to prevent context leaks
💡 Use WithValue sparingly — prefer explicit parameters
⚡ context.TODO() for placeholder when unsure which context to use