golang-context

por samber

Uso idiomático de context.Context en Golang: propagación a través de límites de API, cancelación, tiempos de espera y plazos, valores de ámbito de solicitud, context.WithoutCancel para trabajo en segundo plano que sobrevive a las solicitudes. Aplicar al diseñar propagación de contexto entre capas, depurar contextos filtrados o no expirados, elegir entre context.Background/TODO/WithoutCancel, o almacenar valores en contexto. No para código que simplemente acepta ctx como primer parámetro.

npx skills add https://github.com/samber/cc-skills-golang --skill golang-context

Community default. A company skill that explicitly supersedes samber/cc-skills-golang@golang-context skill takes precedence.

Go context.Context Best Practices

context.Context is Go's mechanism for propagating cancellation signals, deadlines, and request-scoped values across API boundaries and between goroutines. Think of it as the "session" of a request — it ties together every operation that belongs to the same unit of work.

Best Practices Summary

  1. The same context MUST be propagated through the entire request lifecycle: HTTP handler → service → DB → external APIs
  2. ctx MUST be the first parameter, named ctx context.Context
  3. NEVER store context in a struct — pass explicitly through function parameters
  4. NEVER pass nil context — use context.TODO() if unsure
  5. cancel() MUST be called on all control-flow paths for WithCancel/WithTimeout/WithDeadline, unless ownership of the context and cancel function is explicitly returned or transferred
  6. context.Background() MUST only be used at the top level (main, init, tests)
  7. Use context.TODO() as a placeholder when you know a context is needed but don't have one yet
  8. NEVER create a new context.Background() in the middle of a request path
  9. Context value keys MUST be unexported types to prevent collisions
  10. Context values MUST only carry request-scoped metadata — NEVER function parameters
  11. Use context.WithoutCancel (Go 1.21+) when spawning background work that must outlive the parent request

Creating Contexts

SituationUse
Entry point (main, init, test)context.Background()
Function needs context but caller doesn't provide one yetcontext.TODO()
Inside an HTTP handlerr.Context()
Need cancellation controlcontext.WithCancel(parentCtx)
Need a deadline/timeoutcontext.WithTimeout(parentCtx, duration)

Context Propagation: The Core Principle

The most important rule: propagate the same context through the entire call chain. When you propagate correctly, cancelling the parent context cancels all downstream work automatically.

// ✗ Bad — creates a new context, breaking the chain
func (s *OrderService) Create(ctx context.Context, order Order) error {
    return s.db.ExecContext(context.Background(), "INSERT INTO orders ...", order.ID)
}

// ✓ Good — propagates the caller's context
func (s *OrderService) Create(ctx context.Context, order Order) error {
    return s.db.ExecContext(ctx, "INSERT INTO orders ...", order.ID)
}

Deep Dives

  • Cancellation, Timeouts & Deadlines — How cancellation propagates: WithCancel for manual cancellation, WithTimeout for automatic cancellation after a duration, WithDeadline for absolute time deadlines. Patterns for listening (<-ctx.Done()) in concurrent code, AfterFunc callbacks, and WithoutCancel for operations that must outlive their parent request (e.g., audit logs).

  • Context Values & Cross-Service Tracing — Safe context value patterns: unexported key types to prevent namespace collisions, when to use context values (request ID, user ID) vs function parameters. Trace context propagation: OpenTelemetry trace headers, correlation IDs for log aggregation, and marshaling/unmarshaling context across service boundaries.

  • Context in HTTP Servers & Service Calls — HTTP handler context: r.Context() for request-scoped cancellation, middleware integration, and propagating to services. HTTP client patterns: NewRequestWithContext, client timeouts, and retries with context awareness. Database operations: always use *Context variants (QueryContext, ExecContext) to respect deadlines.

Cross-References

  • → See the samber/cc-skills-golang@golang-concurrency skill for goroutine cancellation patterns using context
  • → See the samber/cc-skills-golang@golang-database skill for context-aware database operations (QueryContext, ExecContext)
  • → See the samber/cc-skills-golang@golang-observability skill for trace context propagation with OpenTelemetry
  • → See the samber/cc-skills-golang@golang-design-patterns skill for timeout and resilience patterns

Enforce with Linters

Many context pitfalls are caught automatically by linters: govet, staticcheck. → See the samber/cc-skills-golang@golang-lint skill for configuration and usage.

Más skills de samber

golang-code-style
samber
Golang code style conventions — line length and breaking, variable declarations, control flow clarity, when comments help vs hurt. Use when writing or reviewing Go code, asking about style or clarity, or establishing project coding standards. Not for naming conventions (→ See `samber/cc-skills-golang@golang-naming` skill), linter configuration (→ See `samber/cc-skills-golang@golang-lint` skill), or doc comments (→ See `samber/cc-skills-golang@golang-documentation` skill).
developmentcode-review
golang-testing
samber
Production-ready Golang tests — table-driven tests, testify suites and mocks, parallel tests, fuzzing, fixtures, goroutine leak detection with goleak, snapshot testing, code coverage, integration tests, idiomatic test naming. Use when writing or reviewing Go tests, choosing a testing approach, setting up Go test CI, or debugging flaky/slow tests. For testify-specific APIs see `samber/cc-skills-golang@golang-stretchr-testify`; for measurement methodology see...
developmenttestingcode-review
golang-design-patterns
samber
Patrones de diseño idiomáticos en Golang: opciones funcionales, constructores, flujo y cascada de errores, gestión y ciclo de vida de recursos, apagado elegante, resiliencia, arquitectura, inyección de dependencias, manejo de datos, streaming y más. Aplicar al elegir explícitamente entre patrones arquitectónicos, implementar opciones funcionales, diseñar APIs de constructores, configurar un apagado elegante, aplicar patrones de resiliencia o preguntar qué patrón idiomático de Go se ajusta a un problema específico.
developmentdesigncode-review
golang-error-handling
samber
Idiomatic Golang error handling — creation, wrapping with %w, errors.Is/As, errors.Join, custom error types, sentinel errors, panic/recover, the single handling rule, structured logging with slog, HTTP request logging middleware, and samber/oops for production errors. Built to make logs usable at scale with log aggregation 3rd-party tools. Apply when creating, wrapping, inspecting, or logging errors in Go code. For samber/oops specifics → See `samber/cc-skills-golang@golang-samber-oops`...
developmentcode-review
golang-performance
samber
Patrones y metodología de optimización de rendimiento en Golang: si hay un cuello de botella X, entonces aplica Y. Cubre reducción de asignaciones, eficiencia de CPU, diseño de memoria, ajuste de GC, pooling, caching y optimización de rutas críticas. Úsalo cuando el perfilado o los benchmarks hayan identificado un cuello de botella y necesites el patrón de optimización adecuado para solucionarlo. También úsalo al realizar una revisión de código de rendimiento para sugerir mejoras o benchmarks que ayuden a identificar ganancias rápidas de rendimiento. No es para metodología de medición (→...
developmentcode-review
golang-security
samber
Prácticas recomendadas de seguridad y prevención de vulnerabilidades para Golang. Abarca inyección (SQL, comandos, XSS), criptografía, seguridad del sistema de archivos, seguridad de red, cookies, gestión de secretos, seguridad de memoria y registro. Aplicar al escribir, revisar o auditar código Go por seguridad, o al trabajar en cualquier código riesgoso que involucre criptografía, E/S, gestión de secretos, manejo de entrada de usuario o autenticación. Incluye configuración de herramientas de seguridad.
securitycode-reviewdevelopment
golang-database
samber
Guía completa para el acceso a bases de datos en Go: consultas parametrizadas, escaneo de estructuras, columnas anulables, transacciones, niveles de aislamiento, SELECT FOR UPDATE, pool de conexiones, procesamiento por lotes, propagación de contexto y herramientas de migración. Úsela al escribir, revisar o depurar código Golang que interactúe con PostgreSQL, MariaDB, MySQL o SQLite; para pruebas de bases de datos; o para preguntas sobre database/sql, sqlx o pgx. NO genera esquemas de bases de datos ni SQL de migración.
developmentdatabase
golang-lint
samber
Mejores prácticas de linting y configuración de golangci-lint para proyectos Golang: ejecutar linters, configurar .golangci.yml, suprimir advertencias con directivas nolint, interpretar la salida de lint y seleccionar linters. Úselo al configurar golangci-lint, preguntar sobre advertencias de lint o supresiones nolint, configurar herramientas de calidad de código o elegir linters. También úselo cuando el usuario mencione golangci-lint, go vet, staticcheck o revive.
developmentcode-reviewtesting