golang-context
Propagate Go context.Context cancellation, deadlines, and request-scoped values through APIs. Use when work needs a cancellation contract or context misuse causes leaks or timeouts.
- License 许可
- MIT
- 最近更新
- 2026-11-14
- Stars
- ★ 0
- Forks
- 0
01 前言 Front Matter
- name
- golang-context
- paths
- [ "**/*.go" ]
- license
- MIT
- metadata
- { "author": "samber", "version": "1.3.1", "openclaw": { "emoji": "🔗", "install": [], "homepage": "https://github.com/samber/cc-skills-golang", "requires": { "bins": [ "go" ] } } }
- description
- Propagate Go context.Context cancellation, deadlines, and request-scoped values through APIs. Use when work needs a cancellation contract or context misuse causes leaks or timeouts.
- allowed-tools
- Read Edit Write Glob Grep Bash(go build:*) Bash(go test:*) Bash(go vet:*) Bash(golangci-lint run:*) Bash(git status:*) Bash(git diff:*) Bash(git log:*) Bash(git show:*) Agent
- compatibility
- Designed for Claude Code, Codex or similar harness, and for projects using Golang.
- user-invocable
- true
02 资源文件 4
- 参考文档evals/evals.json13.2 KB
- 参考文档references/cancellation.md5.5 KB
- 参考文档references/http-services.md3.7 KB
- 参考文档references/values-tracing.md2.9 KB
03 SKILL.md 正文
Community default. Company skill explicitly superseding
samber/cc-skills-golang@golang-contextskill takes precedence.
Go context.Context Best Practices
Best Practices Summary
- Propagate same context through whole request lifecycle: HTTP handler → service → DB → external APIs. Any link starting fresh context keeps running after client leaves.
- Take
ctxas first parameter, namedctx context.Context. Fixed position makes context-aware APIs obvious at a glance; linters check it. - Pass context as function parameter, not struct field. Struct outlives its request, so later calls reuse context already cancelled or owned by someone else.
- Pass
context.TODO(), notnilcontext.nilpanics on firstDone()orValue()call, far from caller that passed it. - Call
cancel()on all control-flow paths forWithCancel/WithTimeout/WithDeadline, unless ownership of context and cancel function is explicitly returned or transferred. Uncalledcancel()keeps child attached to parent and leaks its timer until parent finishes. - Create
context.Background()only at top-level entry points (main, init, tests). Deeper in call chain, especially mid-request, it detaches work from caller's deadline and cancellation (propagation break below). - Use
context.TODO()as placeholder when context needed but none exists yet. Marks gap for later fix instead of hiding it behind deliberate-lookingBackground(). - Declare context value keys as unexported types. Plain
stringkey: two packages using"user"silently overwrite each other. - Carry only request-scoped metadata in context values, never function parameters.
Value()results lose compile-time typing and vanish from function signature. - Use
context.WithoutCancel(Go 1.21+) for background work that must outlive parent request. Otherwise handler return cancels just-started audit log or cleanup.
Creating Contexts
| Situation | Use |
|---|---|
| Entry point (main, init, test) | context.Background() |
| Function needs context, caller doesn't provide one yet | context.TODO() |
| Inside HTTP handler | r.Context() |
| Need cancellation control | context.WithCancel(parentCtx) |
| Need deadline/timeout | context.WithTimeout(parentCtx, duration) |
Context Propagation: The Core Principle
Key rule: propagate same context through entire call chain. Then cancelling parent cancels all downstream work automatically.
// ✗ Bad — creates a new context, breaking the chain
func (s *OrderService) Create(ctx context.Context, order Order) error {
_, err := s.db.ExecContext(context.Background(), "INSERT INTO orders ...", order.ID)
return err
}
// ✓ Good — propagates the caller's context
func (s *OrderService) Create(ctx context.Context, order Order) error {
_, err := s.db.ExecContext(ctx, "INSERT INTO orders ...", order.ID)
return err
}
Deep Dives
-
Cancellation, Timeouts & Deadlines — How cancellation propagates:
WithCancel(manual),WithTimeout(after a duration),WithDeadline(absolute time). Listening (<-ctx.Done()) in concurrent code,AfterFunccallbacks,WithoutCancelfor operations that must outlive parent request (e.g., audit logs). -
Context Values & Cross-Service Tracing — Safe value patterns: unexported key types prevent namespace collisions; when to use context values (request ID, user ID) vs function parameters. Trace propagation: OpenTelemetry trace headers, correlation IDs for log aggregation, marshaling/unmarshaling context across service boundaries.
-
Context in HTTP Servers & Service Calls — Handler context:
r.Context()for request-scoped cancellation, middleware, propagation to services. HTTP clients:NewRequestWithContext, client timeouts, context-aware retries. Database: always use*Contextvariants (QueryContext,ExecContext) to respect deadlines.
Cross-References
- → See
samber/cc-skills-golang@golang-concurrencyskill for goroutine cancellation patterns using context - → See
samber/cc-skills-golang@golang-databaseskill for context-aware database operations (QueryContext, ExecContext) - → See
samber/cc-skills-golang@golang-observabilityskill for trace context propagation with OpenTelemetry - → See
samber/cc-skills-golang@golang-design-patternsskill for timeout and resilience patterns
Enforce with Linters
govet and staticcheck linters catch many context pitfalls automatically. → See samber/cc-skills-golang@golang-lint skill for configuration and usage.
04 同仓库更多 Skills
wiki-builder
Create and maintain a local Markdown research wiki (sources with provenance, compiled concept/source pages, index, maintenance log) driven by a per-wiki config. Use when the user wants to start a wiki or knowledge base, ingest sources into one, or query and update it; use wiki-page-writer for a single code deep-dive page.
refactoring-guru
Diagnose a named code smell and apply the smallest behavior-preserving refactoring, with verification before and after and an explicit stop condition. Use for structural refactors (extract, move, consolidate, change ownership), not for feature or bug work; for readability cleanup of recent changes use code-simplification.
legacy-seams
When changing untested legacy code, pin the observed results with characterization tests and open the smallest seam that substitutes only the blocking dependency, separate from any later logic change. Use when a clock, random source, I/O, global, or hidden constructor blocks a test or a safe edit. Use test-driven-development for a new behavior or a bug, refactoring-guru for one named structural refactor after the seam exists, and code-refactoring-tech-debt to choose which legacy to replace.
idea-refine
Refine a raw idea into a one-page brief (problem statement, recommended direction, assumptions to validate, MVP scope, not-doing list) through divergent then convergent thinking. Use when an idea is still vague or you want options and a stress test before committing; use interview-me when the goal itself is unclear and spec-driven-development once the direction is chosen.
code-review-and-quality
Review rubric and approval standard for any change before merge, including code written by you, another agent, or a human: five axes (correctness, readability, architecture, security, performance), change sizing, structural remedies, severity labels, and feedback technique. Use to judge whether a change is fit to merge; use code-review to run a PR or diff review end to end.
code-perfection
Smell and style gate for code you write or change. Bans known code smells (long method, large class, primitive obsession, long parameter list, data clumps, duplicate code, dead code, feature envy, shotgun surgery, flag arguments, message chains) and enforces behavior-preserving structure. On Scala files, enforces worxbend style. Use while implementing, reviewing a diff for smells, or when a smell or style violation is suspected. Routine construction stays with code-complete. SOLID and DRY stay with clean-code-guard. One named structural refactor stays with refactoring-guru.