Go context.Context Best Practices

VerifiedSafe

Idiomatic Go context.Context guide: propagation, cancellation, timeouts, request-scoped values, and context.WithoutCancel for background work.

Sby Skills Guide Bot
DevelopmentIntermediate
10/21/2026
Claude CodeCursorWindsurfCopilotCodex
#golang#context#cancellation#concurrency#best-practices

Recommended for

Automated summary

This skill provides guidance on idiomatic context.Context usage in Go, covering propagation across layers, cancellation, deadlines, and request-scoped values.

Strengths

  • States clear rules for propagating the same context and placing ctx as the first parameter.
  • Covers advanced cases such as context.WithoutCancel, unexported value keys, and AfterFunc callbacks.
  • Includes a practical decision table for Background, TODO, r.Context, WithCancel, and WithTimeout.
  • Scopes itself narrowly and explicitly excludes code that merely accepts a ctx parameter.

Limitations

  • Focuses only on context.Context and does not address broader Go concurrency or error-handling patterns.
  • Its MUST-level rules may be too rigid for legacy code or unusual architectures.
  • The deepest material is delegated to reference files, so the SKILL.md itself is largely a summary.
When to use it

Use it when designing or reviewing a Go call chain that must propagate cancellation, deadlines, or request-scoped values.

When not to use it

Avoid it for simple functions that already accept a ctx and raise no propagation, cancellation, or context-value questions.

Security analysis

Safe
Quality score86/100

The skill is pure instructional documentation on idiomatic context.Context usage. It contains no executable payloads, no network calls, no obfuscation, no secret handling, and no destructive commands. Tool grants (Read/Edit/Write/Glob/Grep plus go/golangci-lint/git/Agent) are appropriately scoped for a Go development skill, and the text never instructs the agent to run shell commands or touch credentials. Only minor note is that Bash(go:*) can transitively run code, which is inherent to Go tooling rather than a red flag here.

Findings
  • •Declared tool set includes Bash(go:*), which can indirectly execute arbitrary code (e.g., `go run`, `go generate`); this is a normal, narrow scope for a Go skill but worth noting
  • •Skill references bundled reference files (./references/*.md) that were not included in the provided content and therefore could not be reviewed
How this analysis is made

Examples

Audit context propagation
Review this Go HTTP handler and service layer for context propagation issues. Point out any places where context.Background() or a new context breaks the request chain.
Choose cancellation strategy
My Go service leaks contexts after requests time out. Help me choose between context.WithTimeout, context.WithCancel, and context.WithoutCancel for cleanup and audit logging.
Store request IDs correctly
Is it appropriate to store a request ID in context.Context in Go? Show the idiomatic unexported key pattern and explain when values should be passed as parameters instead.

name: golang-context description: "Idiomatic context.Context usage in Golang — propagation through API boundaries, cancellation, timeouts and deadlines, request-scoped values, context.WithoutCancel for background work outliving requests. Apply when designing context propagation across layers, debugging leaked or unexpired contexts, choosing between context.Background/TODO/WithoutCancel, or storing values in context. Not for code that merely accepts ctx as first parameter." user-invocable: true license: MIT compatibility: Designed for Claude Code or similar AI coding agents, and for projects using Golang. metadata: author: samber version: "1.2.1" openclaw: emoji: "🔗" homepage: https://github.com/samber/cc-skills-golang requires: bins: - go install: [] allowed-tools: Read Edit Write Glob Grep Bash(go:) Bash(golangci-lint:) Bash(git:*) Agent

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.

// ✗ 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.

From the file to a first result

The download contains exactly the content displayed on this page. This copy may differ from the latest version in the source repository.

View the source and supporting files

This download contains SKILL.md only. Any scripts, references, templates and dependencies are not included. Get the required files from the source, preserving their directory structure, before continuing.

1. Download the file

Download SKILL.md

From the root of a test project, save the file as .skill-downloads/go-context-context-best-practices-mvda87ij/SKILL.md, or use the command below. This folder is for inspecting the skill before installation.

Command for macOS/Linux or WSL: requires a POSIX shell and curl. On Windows without WSL, use the download button and create the folder manually.

mkdir -p '.skill-downloads/go-context-context-best-practices-mvda87ij' && curl --fail --show-error --location 'https://skills-guides.com/api/skills/go-context-context-best-practices-mvda87ij/download' --output '.skill-downloads/go-context-context-best-practices-mvda87ij/SKILL.md.part' && mv '.skill-downloads/go-context-context-best-practices-mvda87ij/SKILL.md.part' '.skill-downloads/go-context-context-best-practices-mvda87ij/SKILL.md'

2. Check prerequisites

Read SKILL.md before using it. If it references scripts or external services, inspect them and prepare the required access in your test environment.

Environment declared by the author: Designed for Claude Code or similar AI coding agents, and for projects using Golang.

Tools declared by the author (check availability in your agent): Read Edit Write Glob Grep Bash(go:*) Bash(golangci-lint:*) Bash(git:*) Agent

No recognized prerequisites section in this file. This does not mean it is self-contained: libraries, tools and access requirements may be mentioned elsewhere in the content or source repository.

The platforms on this page are catalog indications. The paths below follow tool documentation; they do not prove this skill has been run in those tools. No minimum tool version is confirmed for this listing.

3. Load the skill

After inspection, copy the complete folder into your project using one of the commands below, then open a new tool session. The command stops if a folder with the same name already exists: compare the files before replacing it.

Claude Code
test -f '.skill-downloads/go-context-context-best-practices-mvda87ij/SKILL.md' && test -s '.skill-downloads/go-context-context-best-practices-mvda87ij/SKILL.md' && mkdir -p '.claude/skills' && test ! -e '.claude/skills/golang-context' && cp -R '.skill-downloads/go-context-context-best-practices-mvda87ij' '.claude/skills/golang-context'

Cursor
test -f '.skill-downloads/go-context-context-best-practices-mvda87ij/SKILL.md' && test -s '.skill-downloads/go-context-context-best-practices-mvda87ij/SKILL.md' && mkdir -p '.cursor/skills' && test ! -e '.cursor/skills/golang-context' && cp -R '.skill-downloads/go-context-context-best-practices-mvda87ij' '.cursor/skills/golang-context'

Codex
test -f '.skill-downloads/go-context-context-best-practices-mvda87ij/SKILL.md' && test -s '.skill-downloads/go-context-context-best-practices-mvda87ij/SKILL.md' && mkdir -p '.agents/skills' && test ! -e '.agents/skills/golang-context' && cp -R '.skill-downloads/go-context-context-best-practices-mvda87ij' '.agents/skills/golang-context'

OpenSkills

OpenSkills must already be installed. The local install/read procedure is checked with OpenSkills 1.5.0, which requires Node.js ≥ 20.6.0. Catalog slugs are not resolved automatically.

Official OpenSkills installation
openskills install './.skill-downloads/go-context-context-best-practices-mvda87ij'

openskills read 'go-context-context-best-practices-mvda87ij'

Reading should display the installed file content and its base directory. It does not run the skill or install its dependencies.

For an agent that reads AGENTS.md, then sync the index. This command changes AGENTS.md: review the diff before using it.

openskills sync

Manual method or another tool: attach SKILL.md to a conversation, or open it in an agent that can read files. Include any required supporting resources. No universal folder is recognized by every tool.

4. Try a first task

Use a short, synthetic input: an API endpoint, a small document or an interface brief. In a new conversation, attach the file or give the agent its path, then adapt this request:

Read .skill-downloads/go-context-context-best-practices-mvda87ij/SKILL.md and apply its instructions to this example: [describe a test input]. Identify any missing files, dependencies or access. Produce the result requested by the skill without inventing data or running unreviewed scripts.

Expected result: output matching the skill instructions, or a precise list of missing prerequisites. A read confirmation alone does not validate a first use. If an external resource is unavailable, that path remains untested.

Related skills