Context — a Go standard library type for carrying deadlines, cancellation signals, and request-scoped values.
Creating contexts:
1ctx := context.Background() // root2ctx, cancel := context.WithCancel(parent) // manual3ctx, cancel := context.WithTimeout(parent, 5s) // timeout4ctx, cancel := context.WithDeadline(parent, t) // deadline5ctx = context.WithValue(parent, "key", "val") // value6defer cancel()
Practical usage:
1func handler(w http.ResponseWriter, r *http.Request) {2 ctx := r.Context()34 // Timeout for DB query5 dbCtx, cancel := context.WithTimeout(ctx, 3*time.Second)6 defer cancel()78 var user User9 if err := db.QueryRowContext(dbCtx, "SELECT * FROM users WHERE id=$1", id).Scan(&user); err != nil {10 if errors.Is(err, context.DeadlineExceeded) {11 http.Error(w, "timeout", http.StatusGatewayTimeout)12 } else {13 http.Error(w, "error", http.StatusInternalServerError)14 }15 return16 }17 json.NewEncoder(w).Encode(user)18}
Context hierarchy:
When to use context:
Common mistakes:
cancel() (resource leak).context.Background() in library code.defer cancel().