Context — a standard library type (context.Context) that carries deadlines, cancellation signals, and request-scoped values across goroutine boundaries.
Core interfaces:
Deadline() — returns the time when work should be cancelled.Done() — returns a channel that is closed when the context is cancelled.Err() — returns Canceled if the context was cancelled, or DeadlineExceeded if the deadline passed.Value(key) — retrieves a value associated with the context.Creating contexts:
1// Background context (root, no deadline)2ctx := context.Background()34// Context with timeout (5 seconds)5ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)6defer cancel()78// Context with deadline (specific time)9deadline := time.Now().Add(10 * time.Second)10ctx, cancel := context.WithDeadline(context.Background(), deadline)11defer cancel()1213// Context with cancellation (manual)14ctx, cancel := context.WithCancel(context.Background())15defer cancel()1617// Context with value18ctx = context.WithValue(context.Background(), "userID", "12345")
Using context in HTTP handlers:
1func handler(w http.ResponseWriter, r *http.Request) {2 ctx := r.Context() // Get context from request34 // Pass to downstream services5 result, err := fetchUserData(ctx, userID)6 if err != nil {7 // Check if context was cancelled8 if ctx.Err() == context.Canceled {9 return // Client disconnected10 }11 }12}
When to use context:
Common mistakes:
cancel() (causes goroutine leak).context.Background() or context.TODO() in library code (use the context passed to you).WithCancel but never calling cancel().