bateau84/skills

golang-context

Design context propagation, debug leaks, and choose between context types in Go — cancellation, timeouts, deadlines, request-scoped values, and context.WithoutCancel.

View source

How to use

  1. Copy the installation command and review the source package before installing it in your own agent environment.
  2. Check the source document for required tools, credentials and supported hosts.
  3. Describe your input and desired deliverable; review the output against the source material.
npx skills add https://github.com/bateau84/skills --skill golang-context

Before you start

  • Installation does not include a model subscription, API allowance or permission to access your files.
  • Repository stars and installation counts describe activity, not an independent quality or security test.
Original skill document

Rendered from the source repository. Headings, examples, code, tables, links, and referenced images are preserved.

Adapted from samber/cc-skills-golang@golang-context. Pair with golang-common-practice for shared verification guidance.

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.

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 golang-concurrency skill for goroutine cancellation patterns using context
  • → See the golang-database skill for context-aware database operations (QueryContext, ExecContext)
  • → See the golang-observability skill for trace context propagation with OpenTelemetry
  • → See the golang-design-patterns skill for timeout and resilience patterns

Enforce with Linters

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

Related by task

from this repository

More skills

All skills
bateau84
Community

behavioral-spec

Derive bounded, implementation-independent requirements from agreed product intent through goal refinement, coverage lenses, obstacle analysis, provenance tracking, and counterexample checks. Use to select, author, and reconcile Behavioral Requirements (BR), Quality Scenarios (QS), and Obligation Contracts (OC) without expanding scope. Not for concrete API/schema/protocol realization (use architectural-spec) or human-centered stories and scenarios (use user-stories-and-scenarios).

installs
1
GitHub stars
0
Updated
Oct 18
bateau84
Community

desktop-ui-design

Desktop GUI design for native and hybrid applications: platform conventions (macOS HIG, Windows Fluent, GNOME HIG), menus, keyboard shortcuts, window management, session persistence, native vs Electron/Tauri trade-offs, and accessibility APIs. Use for Swift/AppKit, C/WinUI, GTK+, or Electron/Tauri/Flutter desktop design. Add web-ui-design for a web app shipped as a desktop wrapper. Not for browser-only interfaces, terminal applications (use tui-design), or command-line tools (use cli-design).

installs
1
GitHub stars
0
Updated
Oct 18
bateau84
Community

git-commit-discipline

Small coherent commits, explanatory messages, shared-working-tree discipline, and safe undo/recovery. Use when asked to commit, when a diff mixes concerns, when agents share a working tree, or when undoing or recovering Git changes. Not for content conflicts (use git-conflicts).

installs
1
GitHub stars
0
Updated
Oct 18
bateau84
Community

golang-dependency-injection

google/wire, uber-go/dig, uber-go/fx, samber/do, manual constructor injection, and service containers in Go. Use when designing service architecture, setting up dependency injection, refactoring tightly coupled code, or managing singletons and service factories.

installs
1
GitHub stars
0
Updated
Oct 18