Context — a Go standard library package (context) that provides mechanisms for deadline propagation, cancellation signaling, and passing request-scoped values across API boundaries and goroutines.
Key context types:
context.Background() — root context, no deadline, no cancellation.context.TODO() — placeholder when context is not yet available.context.WithCancel(parent) — returns child context and cancel function.context.WithTimeout(parent, duration) — auto-cancels after duration.context.WithDeadline(parent, time) — auto-cancels at specific time.context.WithValue(parent, key, val) — attaches request-scoped data.Practical examples:
1// HTTP handler with context2func handler(w http.ResponseWriter, r *http.Request) {3 ctx := r.Context()45 // Database query with timeout6 dbCtx, cancel := context.WithTimeout(ctx, 3*time.Second)7 defer cancel()89 var user User10 err := db.QueryRowContext(dbCtx, "SELECT * FROM users WHERE id=$1", id).Scan(&user)11 if err != nil {12 if errors.Is(err, context.DeadlineExceeded) {13 http.Error(w, "Request timeout", http.StatusGatewayTimeout)14 return15 }16 http.Error(w, "Internal error", http.StatusInternalServerError)17 return18 }19 json.NewEncoder(w).Encode(user)20}
Propagating cancellation:
1func processOrder(ctx context.Context, orderID string) error {2 // Check if context is already cancelled3 select {4 case <-ctx.Done():5 return ctx.Err()6 default:7 }89 // Pass context to sub-operations10 if err := validateOrder(ctx, orderID); err != nil {11 return fmt.Errorf("validating order: %w", err)12 }13 if err := processPayment(ctx, orderID); err != nil {14 return fmt.Errorf("processing payment: %w", err)15 }16 return nil17}
When to use context:
Common mistakes:
cancel() (causes goroutine/resource leak).context.Background() in library code (use the passed context).defer cancel().