{"id":"b12ee1d0-98db-4af0-9eef-075b452641f6","shortId":"Pk7Ga7","kind":"skill","title":"golang-context","tagline":"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.","description":"> **Community default.** A company skill that explicitly supersedes `samber/cc-skills-golang@golang-context` skill takes precedence.\n\n# Go context.Context Best Practices\n\n`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.\n\n## Best Practices Summary\n\n1. The same context MUST be propagated through the entire request lifecycle: HTTP handler → service → DB → external APIs\n2. `ctx` MUST be the first parameter, named `ctx context.Context`\n3. NEVER store context in a struct — pass explicitly through function parameters\n4. NEVER pass `nil` context — use `context.TODO()` if unsure\n5. `cancel()` MUST always be deferred immediately after `WithCancel`/`WithTimeout`/`WithDeadline`\n6. `context.Background()` MUST only be used at the top level (main, init, tests)\n7. **Use `context.TODO()`** as a placeholder when you know a context is needed but don't have one yet\n8. NEVER create a new `context.Background()` in the middle of a request path\n9. Context value keys MUST be unexported types to prevent collisions\n10. Context values MUST only carry request-scoped metadata — NEVER function parameters\n11. **Use `context.WithoutCancel`** (Go 1.21+) when spawning background work that must outlive the parent request\n\n## Creating Contexts\n\n| Situation | Use |\n| --- | --- |\n| Entry point (main, init, test) | `context.Background()` |\n| Function needs context but caller doesn't provide one yet | `context.TODO()` |\n| Inside an HTTP handler | `r.Context()` |\n| Need cancellation control | `context.WithCancel(parentCtx)` |\n| Need a deadline/timeout | `context.WithTimeout(parentCtx, duration)` |\n\n## Context Propagation: The Core Principle\n\nThe 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.\n\n```go\n// ✗ Bad — creates a new context, breaking the chain\nfunc (s *OrderService) Create(ctx context.Context, order Order) error {\n    return s.db.ExecContext(context.Background(), \"INSERT INTO orders ...\", order.ID)\n}\n\n// ✓ Good — propagates the caller's context\nfunc (s *OrderService) Create(ctx context.Context, order Order) error {\n    return s.db.ExecContext(ctx, \"INSERT INTO orders ...\", order.ID)\n}\n```\n\n## Deep Dives\n\n- **[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).\n\n- **[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.\n\n- **[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.\n\n## Cross-References\n\n- → See the `samber/cc-skills-golang@golang-concurrency` skill for goroutine cancellation patterns using context\n- → See the `samber/cc-skills-golang@golang-database` skill for context-aware database operations (QueryContext, ExecContext)\n- → See the `samber/cc-skills-golang@golang-observability` skill for trace context propagation with OpenTelemetry\n- → See the `samber/cc-skills-golang@golang-design-patterns` skill for timeout and resilience patterns\n\n## Enforce with Linters\n\nMany context pitfalls are caught automatically by linters: `govet`, `staticcheck`. → See the `samber/cc-skills-golang@golang-lint` skill for configuration and usage.","tags":["golang","context","skills","samber","agent","agent-skills","antigravity","claude","claude-code","code","codex","coding"],"capabilities":["skill","source-samber","skill-golang-context","topic-agent","topic-agent-skills","topic-antigravity","topic-claude","topic-claude-code","topic-code","topic-codex","topic-coding","topic-copilot","topic-cursor","topic-gemini","topic-gemini-cli-extension"],"categories":["cc-skills-golang"],"synonyms":[],"warnings":[],"endpointUrl":"https://skills.sh/samber/cc-skills-golang/golang-context","protocol":"skill","transport":"skills-sh","auth":{"type":"none","details":{"cli":"npx skills add samber/cc-skills-golang","source_repo":"https://github.com/samber/cc-skills-golang","install_from":"skills.sh"}},"qualityScore":"0.700","qualityRationale":"deterministic score 0.70 from registry signals: · indexed on github topic:agent-skills · 1725 github stars · SKILL.md body (4,365 chars)","verified":false,"liveness":"unknown","lastLivenessCheck":null,"agentReviews":{"count":0,"score_avg":null,"cost_usd_avg":null,"success_rate":null,"latency_p50_ms":null,"narrative_summary":null,"summary_updated_at":null},"enrichmentModel":"deterministic:skill-github:v1","enrichmentVersion":1,"enrichedAt":"2026-05-18T18:53:00.303Z","embedding":null,"createdAt":"2026-04-18T20:32:02.082Z","updatedAt":"2026-05-18T18:53:00.303Z","lastSeenAt":"2026-05-18T18:53:00.303Z","tsv":"'/references/cancellation.md':359 '/references/http-services.md':454 '/references/values-tracing.md':407 '1':95 '1.21':228 '10':211 '11':224 '2':113 '3':123 '4':135 '5':144 '6':155 '7':168 '8':187 '9':200 'absolut':376 'across':64,445 'afterfunc':386 'aggreg':441 'alway':147,483 'api':65,112 'appli':21 'audit':399 'automat':306,369,557 'awar':480,518 'background':231 'bad':308 'belong':85 'best':47,92 'boundari':66,447 'break':313 'call':292,453 'callback':387 'caller':253,335 'cancel':11,56,145,266,298,302,356,361,366,370,463,504 'carri':216 'caught':556 'chain':293,315 'client':471,474 'code':29,385 'collis':210,418 'communiti':30 'compani':33 'concurr':384,500 'configur':570 'context':3,14,41,98,126,139,178,201,212,240,251,276,288,301,312,337,401,409,422,432,444,448,457,479,485,507,517,532,553 'context-awar':516 'context.background':156,192,248,327 'context.context':5,25,46,49,122,321,343 'context.todo':141,170,259 'context.withcancel':268 'context.withoutcancel':226 'context.withtimeout':273 'control':267 'core':279 'correct':297 'correl':437 'creat':189,239,309,319,341 'creation':9 'cross':18,404,493 'cross-refer':492 'cross-servic':17,403 'ctx':114,121,320,342,349 'ctx.done':382 'databas':481,513,519 'db':110 'deadlin':13,58,358,378,491 'deadline/timeout':272 'deep':354 'default':31 'defer':149 'design':541 'dive':355 'doesn':254 'downstream':304 'durat':275,373 'e.g':398 'enforc':549 'entir':104,291 'entri':243 'error':324,346 'everi':82 'execcontext':488,522 'explicit':36,131 'extern':111 'first':118 'func':316,338 'function':133,222,249,429 'go':28,45,51,227,307 'golang':2,8,40,499,512,527,540,566 'golang-concurr':498 'golang-context':1,39 'golang-databas':511 'golang-design-pattern':539 'golang-lint':565 'golang-observ':526 'good':332 'goroutin':69,503 'govet':560 'handler':108,263,456 'header':436 'http':107,262,450,455,470 'id':425,427,438 'idiomat':4 'immedi':150 'import':283 'init':166,246 'insert':328,350 'insid':260 'integr':465 'key':203,413 'know':176 'level':164 'lifecycl':106 'lint':567 'linter':551,559 'listen':381 'log':400,440 'main':165,245 'mani':552 'manual':365 'marshaling/unmarshaling':443 'mechan':53 'metadata':220 'middl':195 'middlewar':464 'must':99,115,146,157,204,214,234,393 'name':120 'namespac':417 'need':180,250,265,270 'never':124,136,188,221 'new':191,311 'newrequestwithcontext':473 'nil':138 'observ':528 'one':185,257 'opentelemetri':434,535 'oper':83,391,482,520 'order':322,323,330,344,345,352 'order.id':331,353 'orderservic':318,340 'outliv':235,394 'paramet':119,134,223,430 'parent':237,300,396 'parentctx':269,274 'pass':130,137 'path':199 'pattern':379,411,472,505,542,548 'pitfal':554 'placehold':173 'point':244 'practic':48,93 'preced':44 'prevent':209,416 'principl':280 'propag':10,55,101,277,285,296,333,362,433,467,533 'provid':256 'querycontext':487,521 'r.context':264,458 'refer':494 'request':61,78,105,198,218,238,397,424,461 'request-scop':60,217,460 'resili':547 'respect':490 'retri':477 'return':325,347 'rule':284 's.db.execcontext':326,348 'safe':408 'samber/cc-skills-golang':38,497,510,525,538,564 'scope':62,219,462 'see':495,508,523,536,562 'server':451 'servic':19,109,405,446,452,469 'session':75 'signal':57 'situat':241 'skill':34,42,501,514,529,543,568 'skill-golang-context' 'source-samber' 'spawn':230 'staticcheck':561 'store':125 'struct':129 'summari':94 'supersed':37 'take':43 'test':167,247 'think':70 'tie':80 'time':377 'timeout':12,357,475,545 'togeth':81 'top':163 'topic-agent' 'topic-agent-skills' 'topic-antigravity' 'topic-claude' 'topic-claude-code' 'topic-code' 'topic-codex' 'topic-coding' 'topic-copilot' 'topic-cursor' 'topic-gemini' 'topic-gemini-cli-extension' 'trace':20,406,431,435,531 'type':207,414 'unexport':206,412 'unit':89 'unsur':143 'usag':6,572 'use':140,160,169,225,242,421,484,506 'user':426 'valu':15,63,202,213,402,410,423 'variant':486 'vs':428 'withcancel':152,363 'withdeadlin':154,374 'withoutcancel':389 'withtimeout':153,367 'work':23,91,232,305 'yet':186,258","prices":[{"id":"59b3cbfd-a1fe-44b0-86a8-b861a2776ce6","listingId":"b12ee1d0-98db-4af0-9eef-075b452641f6","amountUsd":"0","unit":"free","nativeCurrency":null,"nativeAmount":null,"chain":null,"payTo":null,"paymentMethod":"skill-free","isPrimary":true,"details":{"org":"samber","category":"cc-skills-golang","install_from":"skills.sh"},"createdAt":"2026-04-18T20:32:02.082Z"}],"sources":[{"listingId":"b12ee1d0-98db-4af0-9eef-075b452641f6","source":"github","sourceId":"samber/cc-skills-golang/golang-context","sourceUrl":"https://github.com/samber/cc-skills-golang/tree/main/skills/golang-context","isPrimary":false,"firstSeenAt":"2026-04-18T21:55:05.563Z","lastSeenAt":"2026-05-18T18:53:00.303Z"},{"listingId":"b12ee1d0-98db-4af0-9eef-075b452641f6","source":"skills_sh","sourceId":"samber/cc-skills-golang/golang-context","sourceUrl":"https://skills.sh/samber/cc-skills-golang/golang-context","isPrimary":true,"firstSeenAt":"2026-04-18T20:32:02.082Z","lastSeenAt":"2026-05-07T22:40:26.822Z"}],"details":{"listingId":"b12ee1d0-98db-4af0-9eef-075b452641f6","quickStartSnippet":null,"exampleRequest":null,"exampleResponse":null,"schema":null,"openapiUrl":null,"agentsTxtUrl":null,"citations":[],"useCases":[],"bestFor":[],"notFor":[],"kindDetails":{"org":"samber","slug":"golang-context","github":{"repo":"samber/cc-skills-golang","stars":1725,"topics":["agent","agent-skills","ai","antigravity","claude","claude-code","code","codex","coding","copilot","cursor","gemini","gemini-cli-extension","openclaw","opencode","plugin","skills","skillsmp","vibe-coding"],"license":"mit","html_url":"https://github.com/samber/cc-skills-golang","pushed_at":"2026-05-18T17:36:00Z","description":"🧑‍🎨 A collection of Golang agentic skills that works","skill_md_sha":"f2b44dcaad377eacb822c8eabcaa110df6388a04","skill_md_path":"skills/golang-context/SKILL.md","default_branch":"main","skill_tree_url":"https://github.com/samber/cc-skills-golang/tree/main/skills/golang-context"},"layout":"multi","source":"github","category":"cc-skills-golang","frontmatter":{"name":"golang-context","license":"MIT","description":"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.","compatibility":"Designed for Claude Code or similar AI coding agents, and for projects using Golang."},"skills_sh_url":"https://skills.sh/samber/cc-skills-golang/golang-context"},"updatedAt":"2026-05-18T18:53:00.303Z"}}