What problem does it solve?
Many Go programs misuse context propagation, leading to cancelled work not being observed, resource leaks from forgotten cancel calls, lost tracing information, and background work that is either prematurely cancelled or detached from request metadata. This skill codifies patterns to avoid these pitfalls and to ensure cancellations, deadlines, and request-scoped values behave predictably across goroutines and network boundaries.
Core Features & Use Cases
- Propagation rules: Always accept ctx as the first parameter and pass it through HTTP handlers, services, database calls, and client requests so cancellations and deadlines cascade correctly.
- Cancellation and timeouts: Create cancellable children with WithCancel, WithTimeout, or WithDeadline and always defer cancel to free resources; design per-attempt timeouts and nested timeout hierarchies intentionally.
- Context values & tracing: Store request-scoped metadata like trace IDs using unexported key types and provide typed getters; inject those values into outbound requests for observability.
- Background work patterns: Use context.WithoutCancel (Go 1.21+) to preserve values while detaching cancellation for audit logs or async enqueues; use context.AfterFunc for non-blocking cleanup callbacks.
- APIs and linters: Prefer *Context API variants (QueryContext, ExecContext, NewRequestWithContext) and enable staticcheck/govet rules to catch common mistakes.
- Use Cases: building HTTP handlers that cancel downstream work on client disconnect, repository layers that respect request timeouts, retry logic that scopes timeouts per attempt, and launching audit or cleanup tasks that retain trace metadata.
Quick Start
Inspect a failing Go HTTP handler and update it to obtain the request context from the incoming request, pass that ctx to all downstream database and HTTP client calls, wrap operations with context.WithTimeout and defer cancel for per-attempt deadlines, and use context.TODO as a temporary placeholder when migrating functions.