go-context
Skill72 starsChanged 4 months agoMITView on GitHub
Correct usage of context.Context in Go: propagation, cancellation, timeouts, deadlines, values, and common anti-patterns. Use when: "context usage", "context.Context", "context cancellation", "timeout", "context.WithTimeout", "context.WithCancel", "context values", "context propagation". Not for: concurrency beyond context (go-concurrency-review), HTTP middleware (go-api-design), error handling (go-error-handling).
2 other projects use a version of this.
Adopted by
Most recently taken up by
- muratmirgun/gopherstheir own version, first seen Aug 11, 2026
- cxuu/golang-skillstheir own version, first seen Jun 20, 2026
Other versions2 projects use a version of this.
Word for word · 0
None found.
Edited · 0
None found.
Wrote their own version · 2
- cxuu/golang-skills★ 165same name
- muratmirgun/gophers★ 9same name
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository36 other files it gives its agents.
- AGENTS.mdAGENTS.md
- CLAUDE.mdCLAUDE.md
- .github/copilot-instructions.mdCopilot instructions
- .cursor/rules/go-skills.mdcCursor rule
- go-api-designSkill
- go-architecture-reviewSkill
- go-cliSkill
- go-dependency-injectionSkill
- go-design-patternsSkill
- go-graphqlSkill
- go-grpcSkill
- go-interface-designSkill
- go-openapiSkill
- go-project-layoutSkill
- go-code-reviewSkill
- go-coding-standardsSkill
- go-data-structuresSkill
- go-documentationSkill
- go-error-handlingSkill
- go-modernizeSkill
- go-databaseSkill
- go-concurrency-reviewSkill
- go-defensive-codingSkill
- go-observabilitySkill
- go-performance-reviewSkill
- go-security-auditSkill
- go-troubleshootingSkill
- go-test-qualitySkill
- go-test-table-drivenSkill
- git-commitSkill
- go-binary-sizeSkill
- go-ciSkill
- go-dependency-auditSkill
- go-refactoringSkill
- go-semantic-toolsSkill
- go-skills-routerSkill
The file
We split this skill into the rules it gives an agent
4 rules. About 0 are common, 3 are distinctive, and 1 is very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈3
Distinctive · estimate
This author's own choices. Worth a look.
1
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 34
Read a reference file only when the section below is not enough.
- Very specific: line 178
Before starting work that cannot be interrupted, read the remaining budget with ctx.Deadline() and fail fast when it is too short.
- Distinctive: line 219
No context stored in struct fields
- Distinctive: line 224
Only request-scoped metadata stored in context values (not configs, connections)
≈ “Common” is an estimate: at least 1 in 5 of the 213,895 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Go Context
context.Context controls cancellation, deadlines, and request-scoped values
across API boundaries. Misusing it causes goroutine leaks, orphaned work,
and subtle production bugs.
Detailed reference material, loaded on demand:
references/timeout-budgets.md— dividing a parent's remaining budget, readingctx.Deadline().references/values.md— context key types, accessors, collision traps.references/http-and-testing.md— request context in handlers and middleware, and cancellation tests.
Read a reference file only when the section below is not enough.
1. Core Rules
Context is always the first parameter:
// ✅ Good — context is first
func GetUser(ctx context.Context, id string) (*User, error)
func (s *Service) Process(ctx context.Context, req Request) error
// ❌ Bad — context buried in the middle or end
func GetUser(id string, ctx context.Context) (*User, error)
func Process(req Request, ctx context.Context) errorNEVER store context in a struct:
// ❌ Bad — context stored in struct
type Server struct {
ctx context.Context // NEVER do this
cancel context.CancelFunc
}
// ✅ Good — pass context through method parameters
func (s *Server) Shutdown(ctx context.Context) error {
return s.httpServer.Shutdown(ctx)
}Context represents the lifetime of a single operation, not the lifetime of an object.
NEVER pass nil context:
// ❌ Bad
doSomething(nil, data)
// ✅ Good — use context.TODO() if unsure which context to use
doSomething(context.TODO(), data)
// ✅ Good — use context.Background() for top-level/main
doSomething(context.Background(), data)2. Cancellation
Always defer cancel:
// ✅ Good — cancel called even if operation succeeds
ctx, cancel := context.WithCancel(parentCtx)
defer cancel()
result, err := longOperation(ctx)Failing to call cancel leaks resources (timers, goroutines) until the parent context is cancelled.
Use WithCancel for manual cancellation:
func (s *Supervisor) Run(ctx context.Context) error {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
g, ctx := errgroup.WithContext(ctx)
g.Go(func() error { return s.runWorkerA(ctx) })
g.Go(func() error { return s.runWorkerB(ctx) })
// If any worker returns an error, errgroup cancels ctx,
// which signals all other workers to stop.
return g.Wait()
}Check context cancellation in loops:
// ✅ Good — respects cancellation
func processItems(ctx context.Context, items []Item) error {
for _, item := range items {
if err := ctx.Err(); err != nil {
return fmt.Errorf("processing cancelled: %w", err)
}
if err := process(ctx, item); err != nil {
return fmt.Errorf("process item %s: %w", item.ID, err)
}
}
return nil
}
// ❌ Bad — runs to completion even if cancelled
func processItems(ctx context.Context, items []Item) error {
for _, item := range items {
process(ctx, item) // ignores ctx cancellation between items
}
return nil
}3. Timeouts and Deadlines
WithTimeout for duration-based limits:
func (c *Client) FetchUser(ctx context.Context, id string) (*User, error) {
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.url+"/users/"+id, nil)
if err != nil {
return nil, fmt.Errorf("create request: %w", err)
}
resp, err := c.httpClient.Do(req)
if err != nil {
return nil, fmt.Errorf("fetch user %s: %w", id, err)
}
defer resp.Body.Close()
// ...
}WithDeadline for absolute time limits:
// Use when coordinating with external deadlines (SLAs, cron windows)
deadline := time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC)
ctx, cancel := context.WithDeadline(ctx, deadline)
defer cancel()Timeout budgets
A child timeout spends part of the parent's budget; it never extends it. A 5s DB call and a 10s API call inside a 30s request handler are a budget. A 60s child under a parent with 5s left silently fires at the parent's deadline, which reads as a bug at 3am.
Before starting work that cannot be interrupted, read the remaining budget
with ctx.Deadline() and fail fast when it is too short.
Examples in references/timeout-budgets.md.
4. Context Values
Store only request-scoped metadata: request ID, trace or span ID, the authenticated user, a request-scoped logger. Never a database connection, configuration, or anything the function could take as an explicit parameter.
Keys must be an unexported type, never a string — a string key can be
overwritten by any other package in the process. Export accessor functions
so callers never type-assert on ctx.Value themselves.
Examples in references/values.md.
5. Context in HTTP Handlers and Tests
Handlers take r.Context() and pass it downstream. A cancelled request means
the client disconnected: return without writing a response. Middleware
attaches values with r.WithContext(ctx).
Tests wrap the call under test in context.WithTimeout so a hang fails the
test instead of blocking the suite, and assert errors.Is(err,
context.Canceled) to prove cancellation is honoured.
Examples in references/http-and-testing.md.
6. context.Background() vs context.TODO()
| Function | When to use |
context.Background() | Top-level: main(), init(), test setup. Intentional root context. |
context.TODO() | Placeholder when you don't know which context to use yet. Signals "this needs to be fixed". |
context.TODO() is a code smell in production code — replace it before shipping.
Verification Checklist
context.Contextis the first parameter in all functions that accept it- No context stored in struct fields
defer cancel()called immediately afterWithCancel,WithTimeout,WithDeadline- Long loops check
ctx.Err()between iterations - Child timeouts don't exceed parent timeout budget
- Context values use unexported key types with accessor functions
- Only request-scoped metadata stored in context values (not configs, connections)
- HTTP handlers use
r.Context()and pass it downstream - No
nilcontext passed — usecontext.TODO()orcontext.Background() - Tests use
context.WithTimeoutto prevent hanging
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

