{"id":"d2cd5f1d-d667-45f1-b39d-517d14b6567f","shortId":"Wztqm8","kind":"skill","title":"go-context","tagline":"Use when working with context.Context in Go — placement in signatures, propagating cancellation and deadlines, and storing values in context vs parameters. Also use when cancelling long-running operations, setting timeouts, or passing request-scoped data, even if they don't menti","description":"# Go Context Usage\n\n## Context as First Parameter\n\nFunctions that use a Context should accept it as their **first parameter**:\n\n```go\nfunc F(ctx context.Context, /* other arguments */) error\nfunc ProcessRequest(ctx context.Context, req *Request) (*Response, error)\n```\n\nThis is a strong convention in Go that makes context flow visible and consistent\nacross codebases.\n\n---\n\n## Don't Store Context in Structs\n\nDo not add a Context member to a struct type. Instead, pass `ctx` as a parameter\nto each method that needs it:\n\n```go\n// Bad: Context stored in struct\ntype Worker struct {\n    ctx context.Context  // Don't do this\n}\n\n// Good: Context passed to methods\ntype Worker struct{ /* ... */ }\n\nfunc (w *Worker) Process(ctx context.Context) error {\n    // Context explicitly passed — lifetime clear\n}\n```\n\n**Exception**: Methods whose signature must match an interface in the standard\nlibrary or a third-party library may need to work around this.\n\n---\n\n## Don't Create Custom Context Types\n\nDo not create custom Context types or use interfaces other than `context.Context`\nin function signatures:\n\n```go\n// Bad: Custom context type\ntype MyContext interface {\n    context.Context\n    GetUserID() string\n}\n\n// Good: Use standard context.Context with value extraction\nfunc Process(ctx context.Context) error {\n    userID := GetUserID(ctx)\n}\n```\n\n---\n\n## Where to Put Application Data\n\nConsider these options in order of preference:\n\n1. **Function parameters** — most explicit and type-safe\n2. **Receiver** — for data that belongs to the type\n3. **Globals** — for truly global configuration (use sparingly)\n4. **Context value** — only for request-scoped data\n\nContext values are appropriate for:\n- Request IDs and trace IDs\n- Authentication/authorization info that flows with requests\n- Deadlines and cancellation signals\n\nContext values are **not** appropriate for:\n- Optional function parameters\n- Data that could be passed explicitly\n- Configuration that doesn't vary per-request\n\n---\n\n## Common Patterns\n\n> Read [references/PATTERNS.md](references/PATTERNS.md) when deriving contexts (WithTimeout, WithCancel, WithDeadline), checking cancellation in loops or HTTP handlers, using context values with typed keys, or needing the quick reference table.\n\n### Deriving Contexts\n\nAlways `defer cancel()` immediately after creating a derived context:\n\n```go\nctx, cancel := context.WithTimeout(ctx, 5*time.Second)\ndefer cancel()\n```\n\n### Checking Cancellation\n\n```go\nselect {\ncase <-ctx.Done():\n    return ctx.Err()\ndefault:\n    // Do work\n}\n```\n\n### Context Immutability\n\nContexts are immutable — it's safe to pass the same `ctx` to multiple\nconcurrent calls that share the same deadline and cancellation signal.\n\n---\n\n## Related Skills\n\n- **Goroutine coordination**: See [go-concurrency](../go-concurrency/SKILL.md) when using context for goroutine cancellation, select-based timeouts, or errgroup\n- **Error handling**: See [go-error-handling](../go-error-handling/SKILL.md) when deciding how to wrap or return `ctx.Err()` cancellation errors\n- **Interface design**: See [go-interfaces](../go-interfaces/SKILL.md) when designing APIs that accept context alongside interfaces\n- **Request-scoped logging**: See [go-logging](../go-logging/SKILL.md) when injecting loggers into context or adding request IDs to structured log output","tags":["context","golang","skills","cxuu","agent-skills","ai-agent","ai-assistant","claude","claude-code","codex","cursor","llm"],"capabilities":["skill","source-cxuu","skill-go-context","topic-agent-skills","topic-ai-agent","topic-ai-assistant","topic-claude","topic-claude-code","topic-codex","topic-cursor","topic-golang","topic-llm"],"categories":["golang-skills"],"synonyms":[],"warnings":[],"endpointUrl":"https://skills.sh/cxuu/golang-skills/go-context","protocol":"skill","transport":"skills-sh","auth":{"type":"none","details":{"cli":"npx skills add cxuu/golang-skills","source_repo":"https://github.com/cxuu/golang-skills","install_from":"skills.sh"}},"qualityScore":"0.491","qualityRationale":"deterministic score 0.49 from registry signals: · indexed on github topic:agent-skills · 82 github stars · SKILL.md body (3,323 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-02T12:55:17.624Z","embedding":null,"createdAt":"2026-04-18T22:13:08.455Z","updatedAt":"2026-05-02T12:55:17.624Z","lastSeenAt":"2026-05-02T12:55:17.624Z","tsv":"'/go-concurrency/skill.md':416 '/go-error-handling/skill.md':436 '/go-interfaces/skill.md':453 '/go-logging/skill.md':470 '1':244 '2':253 '3':262 '4':270 '5':368 'accept':60,458 'across':96 'ad':477 'add':106 'alongsid':460 'also':25 'alway':354 'api':456 'applic':235 'appropri':282,303 'argument':72 'around':183 'authentication/authorization':289 'bad':127,207 'base':425 'belong':258 'call':399 'cancel':15,28,297,334,356,365,371,373,406,422,445 'case':376 'check':333,372 'clear':160 'codebas':97 'common':322 'concurr':398,415 'configur':267,314 'consid':237 'consist':95 'context':3,22,48,50,58,91,101,108,128,142,156,189,195,209,271,279,299,329,341,353,362,383,385,419,459,475 'context.context':8,70,77,136,154,202,214,220,227 'context.withtimeout':366 'convent':86 'coordin':411 'could':310 'creat':187,193,359 'ctx':69,76,116,135,153,226,231,364,367,395 'ctx.done':377 'ctx.err':379,444 'custom':188,194,208 'data':40,236,256,278,308 'deadlin':17,295,404 'decid':438 'default':380 'defer':355,370 'deriv':328,352,361 'design':448,455 'doesn':316 'errgroup':428 'error':73,81,155,228,429,434,446 'even':41 'except':161 'explicit':157,248,313 'extract':223 'f':68 'first':52,64 'flow':92,292 'func':67,74,149,224 'function':54,204,245,306 'getuserid':215,230 'global':263,266 'go':2,10,47,66,88,126,206,363,374,414,433,451,468 'go-concurr':413 'go-context':1 'go-error-handl':432 'go-interfac':450 'go-log':467 'good':141,217 'goroutin':410,421 'handl':430,435 'handler':339 'http':338 'id':285,288,479 'immedi':357 'immut':384,387 'info':290 'inject':472 'instead':114 'interfac':168,199,213,447,452,461 'key':345 'librari':172,178 'lifetim':159 'log':465,469,482 'logger':473 'long':30 'long-run':29 'loop':336 'make':90 'match':166 'may':179 'member':109 'menti':46 'method':122,145,162 'multipl':397 'must':165 'mycontext':212 'need':124,180,347 'oper':32 'option':239,305 'order':241 'output':483 'paramet':24,53,65,119,246,307 'parti':177 'pass':36,115,143,158,312,392 'pattern':323 'per':320 'per-request':319 'placement':11 'prefer':243 'process':152,225 'processrequest':75 'propag':14 'put':234 'quick':349 'read':324 'receiv':254 'refer':350 'references/patterns.md':325,326 'relat':408 'req':78 'request':38,79,276,284,294,321,463,478 'request-scop':37,275,462 'respons':80 'return':378,443 'run':31 'safe':252,390 'scope':39,277,464 'see':412,431,449,466 'select':375,424 'select-bas':423 'set':33 'share':401 'signal':298,407 'signatur':13,164,205 'skill':409 'skill-go-context' 'source-cxuu' 'spare':269 'standard':171,219 'store':19,100,129 'string':216 'strong':85 'struct':103,112,131,134,148 'structur':481 'tabl':351 'third':176 'third-parti':175 'time.second':369 'timeout':34,426 'topic-agent-skills' 'topic-ai-agent' 'topic-ai-assistant' 'topic-claude' 'topic-claude-code' 'topic-codex' 'topic-cursor' 'topic-golang' 'topic-llm' 'trace':287 'truli':265 'type':113,132,146,190,196,210,211,251,261,344 'type-saf':250 'usag':49 'use':4,26,56,198,218,268,340,418 'userid':229 'valu':20,222,272,280,300,342 'vari':318 'visibl':93 'vs':23 'w':150 'whose':163 'withcancel':331 'withdeadlin':332 'withtimeout':330 'work':6,182,382 'worker':133,147,151 'wrap':441","prices":[{"id":"bcff708a-d106-49b5-a6b3-30bdac7b132f","listingId":"d2cd5f1d-d667-45f1-b39d-517d14b6567f","amountUsd":"0","unit":"free","nativeCurrency":null,"nativeAmount":null,"chain":null,"payTo":null,"paymentMethod":"skill-free","isPrimary":true,"details":{"org":"cxuu","category":"golang-skills","install_from":"skills.sh"},"createdAt":"2026-04-18T22:13:08.455Z"}],"sources":[{"listingId":"d2cd5f1d-d667-45f1-b39d-517d14b6567f","source":"github","sourceId":"cxuu/golang-skills/go-context","sourceUrl":"https://github.com/cxuu/golang-skills/tree/main/skills/go-context","isPrimary":false,"firstSeenAt":"2026-04-18T22:13:08.455Z","lastSeenAt":"2026-05-02T12:55:17.624Z"}],"details":{"listingId":"d2cd5f1d-d667-45f1-b39d-517d14b6567f","quickStartSnippet":null,"exampleRequest":null,"exampleResponse":null,"schema":null,"openapiUrl":null,"agentsTxtUrl":null,"citations":[],"useCases":[],"bestFor":[],"notFor":[],"kindDetails":{"org":"cxuu","slug":"go-context","github":{"repo":"cxuu/golang-skills","stars":82,"topics":["agent-skills","ai-agent","ai-assistant","claude","claude-code","codex","cursor","go","golang","llm"],"license":"apache-2.0","html_url":"https://github.com/cxuu/golang-skills","pushed_at":"2026-03-15T19:32:10Z","description":"AI Agent Skills for idiomatic, production-ready Go code, distilled from Google, Uber, Community","skill_md_sha":"320b2d566ddc515ad9cd20e46864ea75d8d0d973","skill_md_path":"skills/go-context/SKILL.md","default_branch":"main","skill_tree_url":"https://github.com/cxuu/golang-skills/tree/main/skills/go-context"},"layout":"multi","source":"github","category":"golang-skills","frontmatter":{"name":"go-context","license":"Apache-2.0","description":"Use when working with context.Context in Go — placement in signatures, propagating cancellation and deadlines, and storing values in context vs parameters. Also use when cancelling long-running operations, setting timeouts, or passing request-scoped data, even if they don't mention context.Context directly. Does not cover goroutine lifecycle or sync primitives (see go-concurrency).","compatibility":"Requires Go 1.7+ (context moved to standard library in Go 1.7)"},"skills_sh_url":"https://skills.sh/cxuu/golang-skills/go-context"},"updatedAt":"2026-05-02T12:55:17.624Z"}}