Skillshub golang-context
Idiomatic context.Context usage in Golang — creation, propagation, cancellation, timeouts, deadlines, context values, and cross-service tracing. Apply when working with context.Context in any Go code.
git clone https://github.com/ComeOnOliver/skillshub
T=$(mktemp -d) && git clone --depth=1 https://github.com/ComeOnOliver/skillshub "$T" && mkdir -p ~/.claude/skills && cp -r "$T/skills/Harmeet10000/skills/golang-context" ~/.claude/skills/comeonoliver-skillshub-golang-context && rm -rf "$T"
skills/Harmeet10000/skills/golang-context/SKILL.mdCommunity default. A company skill that explicitly supersedes
skill takes precedence.samber/cc-skills-golang@golang-context
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
- The same context MUST be propagated through the entire request lifecycle: HTTP handler → service → DB → external APIs
MUST be the first parameter, namedctxctx context.Context- NEVER store context in a struct — pass explicitly through function parameters
- NEVER pass
context — usenil
if unsurecontext.TODO()
MUST always be deferred immediately aftercancel()
/WithCancel
/WithTimeoutWithDeadline
MUST only be used at the top level (main, init, tests)context.Background()- Use
as a placeholder when you know a context is needed but don't have one yetcontext.TODO() - NEVER create a new
in the middle of a request pathcontext.Background() - Context value keys MUST be unexported types to prevent collisions
- Context values MUST only carry request-scoped metadata — NEVER function parameters
- Use
(Go 1.21+) when spawning background work that must outlive the parent requestcontext.WithoutCancel
Creating Contexts
| Situation | Use |
|---|---|
| Entry point (main, init, test) | |
| Function needs context but caller doesn't provide one yet | |
| Inside an HTTP handler | |
| Need cancellation control | |
| Need a deadline/timeout | |
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:
for manual cancellation,WithCancel
for automatic cancellation after a duration,WithTimeout
for absolute time deadlines. Patterns for listening (WithDeadline
) in concurrent code,<-ctx.Done()
callbacks, andAfterFunc
for operations that must outlive their parent request (e.g., audit logs).WithoutCancel -
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:
for request-scoped cancellation, middleware integration, and propagating to services. HTTP client patterns:r.Context()
, client timeouts, and retries with context awareness. Database operations: always useNewRequestWithContext
variants (*Context
,QueryContext
) to respect deadlines.ExecContext
Cross-References
- → See the
skill for goroutine cancellation patterns using contextsamber/cc-skills-golang@golang-concurrency - → See the
skill for context-aware database operations (QueryContext, ExecContext)samber/cc-skills-golang@golang-database - → See the
skill for trace context propagation with OpenTelemetrysamber/cc-skills-golang@golang-observability - → See the
skill for timeout and resilience patternssamber/cc-skills-golang@golang-design-patterns
Enforce with Linters
Many context pitfalls are caught automatically by linters:
govet, staticcheck. → See the samber/cc-skills-golang@golang-linter skill for configuration and usage.