# Golang Context > Uso idiomático de context.Context en Go: propagación entre capas, cancelación, timeouts, deadlines, valores en el contexto y context.WithoutCancel para trabajo en segundo plano. Fuente: https://skillsagentes.com/skills/samber/cc-skills-golang/golang-context Markdown: https://skillsagentes.com/skills/samber/cc-skills-golang/golang-context.md Repositorio: https://github.com/samber/cc-skills-golang Autor: samber Licencia: MIT Actualizado: hace 3 meses Coste de contexto: 111 tok instalada, 1.4k tok al activarse, 7.8k tok con todos los archivos del bundle Bundle: 5 archivos, 30 KB Permisos que pide: read edit write glob grep bash(go:*) bash(golangci-lint:*) bash(git:*) agent ## Instalación Un skill son archivos markdown: los mismos archivos valen para cualquier agente y lo único que cambia es el directorio de destino, es decir la bandera `--agent`. Añade `-g` para instalarlo en todos los proyectos de la máquina. ```bash # Claude Code npx -y skills add samber/cc-skills-golang --skill golang-context --agent claude-code # Cursor npx -y skills add samber/cc-skills-golang --skill golang-context --agent cursor # Codex npx -y skills add samber/cc-skills-golang --skill golang-context --agent codex # Gemini CLI npx -y skills add samber/cc-skills-golang --skill golang-context --agent gemini # Windsurf npx -y skills add samber/cc-skills-golang --skill golang-context --agent windsurf # Cline npx -y skills add samber/cc-skills-golang --skill golang-context --agent cline ``` ## Qué hace - Aplica reglas de propagación de context.Context a través de capas: handler HTTP → servicio → DB → APIs externas - Guía la elección entre context.Background, context.TODO y context.WithoutCancel según el caso - Establece patrones para cancelación, timeouts y deadlines con WithCancel/WithTimeout/WithDeadline - Define reglas para almacenar valores en el contexto usando claves de tipo no exportado ## Cuándo usarla - Al diseñar la propagación de contexto entre capas - Al depurar contextos filtrados o no expirados - Al elegir entre context.Background/TODO/WithoutCancel - Al almacenar valores en el contexto ## Cuándo no - Para código que simplemente acepta ctx como primer parámetro ## Qué la activa - "Revisa cómo propago el context.Context en este servicio Go" - "¿Debería usar context.Background() o context.TODO() aquí?" - "Ayúdame a evitar fugas de contexto en mi handler HTTP" - "Cómo uso context.WithoutCancel para trabajo en segundo plano" ## Antes de instalar - Requiere el binario go instalado y un proyecto en Golang. ## Archivos - SKILL.md — 5 KB - evals/evals.json — 13 KB - references/cancellation.md — 5 KB - references/http-services.md — 4 KB - references/values-tracing.md — 3 KB ## SKILL.md Reproducido tal cual desde samber/cc-skills-golang bajo MIT. Esta sección es el documento original y está en inglés. > **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 | Situation | Use | | --- | --- | | Entry point (main, init, test) | `context.Background()` | | Function needs context but caller doesn't provide one yet | `context.TODO()` | | Inside an HTTP handler | `r.Context()` | | Need cancellation control | `context.WithCancel(parentCtx)` | | Need a deadline/timeout | `context.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. ```go // ✗ 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](./references/cancellation.md)** — 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](./references/values-tracing.md)** — 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](./references/http-services.md)** — 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. ## Dónde encaja - Categoría: [Herramientas para desarrolladores](https://skillsagentes.com/categorias/herramientas-desarrollo.md) — Skills que cambian cómo tu agente escribe, revisa y despliega código. - Creador: [samber](https://skillsagentes.com/creators/samber.md) — 0 skills en el directorio - [Todas las skills](https://skillsagentes.com/skills.md) - [Ranking de instalaciones](https://skillsagentes.com/ranking.md) ## Otras skills del mismo repositorio - [Golang Lint](https://skillsagentes.com/skills/samber/cc-skills-golang/golang-lint.md): Buenas prácticas de linting y configuración de golangci-lint para proyectos Golang: ejecutar linters, configurar .golangci.yml, suprimir avisos con nolint, interpretar salidas y elegir linters. - [Golang How To](https://skillsagentes.com/skills/samber/cc-skills-golang/golang-how-to.md): Orquestador de skills de Golang, siempre activo en cualquier tarea de código, revisión, debug o setup: carga las skills más relevantes de samber/cc-skills-golang, a menudo varias a la vez. - [Golang Benchmark](https://skillsagentes.com/skills/samber/cc-skills-golang/golang-benchmark.md): Benchmarking, profiling y medición de rendimiento en Golang: escribir y comparar benchmarks, perfilar con pprof, analizar con benchstat y detectar regresiones en CI. - [Golang Testing](https://skillsagentes.com/skills/samber/cc-skills-golang/golang-testing.md): Tests de Golang listos para producción: table-driven, suites y mocks con testify, tests paralelos, fuzzing, fixtures, detección de fugas de goroutines con goleak, snapshot testing, cobertura, tests de integración. - [Golang Performance](https://skillsagentes.com/skills/samber/cc-skills-golang/golang-performance.md): Patrones y metodología de optimización de rendimiento en Golang: si hay cuello de botella X, aplica el patrón Y, una vez que profiling o benchmarks ya lo identificaron. ## Skills relacionadas - [Golang Samber Hot](https://skillsagentes.com/skills/samber/cc-skills-golang/golang-samber-hot.md): Caché en memoria en Golang con samber/hot: algoritmos de expulsión (LRU, LFU, TinyLFU, S3FIFO, ARC, TwoQueue, SIEVE, FIFO), TTL, loaders, sharding y métricas Prometheus. - [Golang Samber Lo](https://skillsagentes.com/skills/samber/cc-skills-golang/golang-samber-lo.md): Helpers funcionales para Go con samber/lo: 500+ funciones genéricas type-safe para slices, maps, canales, strings, math, tuplas y concurrencia. - [Golang Samber Mo](https://skillsagentes.com/skills/samber/cc-skills-golang/golang-samber-mo.md): Tipos monádicos para Golang con samber/mo — Option, Result, Either, Future, IO, Task y State para valores nulos seguros, manejo de errores y composición funcional. - [Golang Samber Slog](https://skillsagentes.com/skills/samber/cc-skills-golang/golang-samber-slog.md): Extensiones de logging estructurado para Go con paquetes samber/slog-****: pipelines multi-handler, sampling, formateo de atributos, middleware HTTP y enrutamiento a backends como Datadog, Sentry o Loki. - [Golang Spf13 Viper](https://skillsagentes.com/skills/samber/cc-skills-golang/golang-spf13-viper.md): Librería de configuración en Go con spf13/viper: precedencia en capas (flag > env > archivo > KV > default), BindPFlag, AutomaticEnv, Unmarshal con mapstructure, Sub, WatchConfig y aislamiento en tests. --- Skills Agentes · [Índice de páginas en markdown](https://skillsagentes.com/sitemap.md) · [Inicio](https://skillsagentes.com/index.md)