
Go Context
- 903 installs
- 137 repo stars
- Updated June 20, 2026
- cxuu/golang-skills
go-context is a Go agent skill that enforces correct idiomatic context.Context usage for developers writing Go services, APIs, and long-running operations with cancellation, deadlines, and request-scoped data.
About
go-context is an Apache-2.0 skill from cxuu/golang-skills that guides idiomatic use of context.Context in Go backends. The skill enforces context as the first parameter in function signatures, proper propagation of cancellation and deadlines, and storing values in context versus explicit parameters. It applies when cancelling long-running operations, setting timeouts, or passing request-scoped data—even when the user does not mention context.Context directly. The skill requires Go 1.7+ when context moved to the standard library and cites the Go Wiki CodeReviewComments as its source. It explicitly excludes goroutine lifecycle and sync primitives, which belong to the sibling go-concurrency skill.
- Enforces context.Context as the first parameter in function signatures
- Prevents storing Context in struct types and shows correct method patterns
- Guides propagation of cancellation, deadlines, and request-scoped values
- Covers when to use context even if the word Context is not explicitly mentioned
- References official Go Wiki CodeReviewComments conventions
Go Context by the numbers
- 903 all-time installs (skills.sh)
- +38 installs in the week ending Aug 4, 2026 (Skillselion tracking)
- Ranked #436 of 4,347 Backend & APIs skills by installs in the Skillselion catalog
- Security screen: LOW risk (skills.sh audit)
- Data as of Aug 5, 2026 (Skillselion catalog sync)
npx skills add https://github.com/cxuu/golang-skills --skill go-contextAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 903 |
|---|---|
| repo stars | ★ 137 |
| Security audit | 3 / 3 scanners passed |
| Last updated | June 20, 2026 |
| Repository | cxuu/golang-skills ↗ |
How do you use context.Context correctly in Go?
Ensure correct and idiomatic use of context.Context when writing Go services, APIs, and long-running operations.
Who is it for?
Go backend developers writing HTTP services, gRPC handlers, or long-running jobs who need idiomatic context propagation and timeout handling.
Skip if: Developers working only on goroutine pools, sync primitives, or frontend code where context.Context does not apply.
When should I use this skill?
User writes Go code involving timeouts, cancellation, request-scoped values, or context.Context placement in function signatures.
What you get
Go functions with context as first parameter, propagated cancellation/deadlines, and properly scoped context values instead of parameter misuse.
- Idiomatic Go functions with context
- Correct cancellation and deadline patterns
By the numbers
- Requires Go 1.7+ when context joined the standard library
- Sources guidance from Go Wiki CodeReviewComments
Files
Go Context Usage
Compatibility: context has been in the standard library since Go 1.7.Resource Routing
references/PATTERNS.md- Read when deriving contexts, checking cancellation, handling HTTP request contexts, or using typed context-value keys.
Context as First Parameter
Functions that use a Context should accept it as their first parameter:
func F(ctx context.Context, /* other arguments */) error
func ProcessRequest(ctx context.Context, req *Request) (*Response, error)This is a strong convention in Go that makes context flow visible and consistent across codebases.
---
Don't Store Context in Structs
Do not add a Context member to a struct type. Instead, pass ctx as a parameter to each method that needs it:
// Bad: Context stored in struct
type Worker struct {
ctx context.Context // Don't do this
}
// Good: Context passed to methods
type Worker struct{ /* ... */ }
func (w *Worker) Process(ctx context.Context) error {
// Context explicitly passed — lifetime clear
}Exception: Methods whose signature must match an interface in the standard library or a third-party library may need to work around this.
---
Don't Create Custom Context Types
Do not create custom Context types or use interfaces other than context.Context in function signatures:
// Bad: Custom context type
type MyContext interface {
context.Context
GetUserID() string
}
// Good: Use standard context.Context with value extraction
func Process(ctx context.Context) error {
userID := GetUserID(ctx)
}---
Where to Put Application Data
Consider these options in order of preference:
1. Function parameters — most explicit and type-safe 2. Receiver — for data that belongs to the type 3. Globals — for truly global configuration (use sparingly) 4. Context value — only for request-scoped data
Context values are appropriate for:
- Request IDs and trace IDs
- Authentication/authorization info that flows with requests
- Deadlines and cancellation signals
Context values are not appropriate for:
- Optional function parameters
- Data that could be passed explicitly
- Configuration that doesn't vary per-request
---
Common Patterns
Deriving Contexts
Always defer cancel() immediately after creating a derived context:
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()Checking Cancellation
select {
case <-ctx.Done():
return ctx.Err()
default:
// Do work
}Context Immutability
Contexts are immutable — it's safe to pass the same ctx to multiple concurrent calls that share the same deadline and cancellation signal.
---
Related Skills
- Goroutine coordination: See go-concurrency when using context for goroutine cancellation, select-based timeouts, or errgroup
- Error handling: See go-error-handling when deciding how to wrap or return
ctx.Err()cancellation errors - Interface design: See go-interfaces when designing APIs that accept context alongside interfaces
- Request-scoped logging: See go-logging when injecting loggers into context or adding request IDs to structured log output
Context Patterns
Common patterns for deriving, checking, and propagating context.Context.
Contents
- Context Immutability
- When to Use context.Background()
- Deriving Contexts
- Checking Cancellation
- Respecting Cancellation in HTTP Handlers
- Context Value Best Practices
- Quick Reference
Context Immutability
Contexts are immutable. It's safe to pass the same ctx to multiple calls that share the same deadline, cancellation signal, credentials, and parent trace:
// Safe: same context to sequential calls
func ProcessBatch(ctx context.Context, items []Item) error {
for _, item := range items {
if err := process(ctx, item); err != nil {
return err
}
}
return nil
}
// Safe: same context to concurrent calls
func ProcessConcurrently(ctx context.Context, a, b *Data) error {
g, ctx := errgroup.WithContext(ctx)
g.Go(func() error { return processA(ctx, a) })
g.Go(func() error { return processB(ctx, b) })
return g.Wait()
}---
When to Use context.Background()
Use context.Background() only for functions that are never request-specific:
func main() {
ctx := context.Background()
if err := run(ctx); err != nil {
log.Fatal(err)
}
}
func startBackgroundWorker() {
ctx := context.Background()
go worker(ctx)
}Default to passing a Context even if you think you don't need to. Only use context.Background() directly if you have a good reason why passing a context would be a mistake:
func LoadConfig(ctx context.Context) (*Config, error) {
// Even if not using ctx now, accepting it allows future
// additions without API changes
}---
Deriving Contexts
// Add timeout — cancel fires after duration elapses
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
// Add cancellation — caller controls when to cancel
ctx, cancel := context.WithCancel(ctx)
defer cancel()
// Add deadline — cancel fires at a specific wall-clock time
ctx, cancel := context.WithDeadline(ctx, time.Now().Add(time.Hour))
defer cancel()
// Add value (use sparingly — only for request-scoped data)
ctx = context.WithValue(ctx, requestIDKey, reqID)Always `defer cancel()` immediately after creating a derived context. This ensures resources are released even if the function returns early.
Nested Derivation
Derived contexts form a tree. Cancelling a parent cancels all its children:
func handleRequest(ctx context.Context) error {
// Parent timeout for the whole request
ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()
// Tighter timeout for the database call
dbCtx, dbCancel := context.WithTimeout(ctx, 5*time.Second)
defer dbCancel()
data, err := queryDB(dbCtx)
if err != nil {
return err
}
// Remaining time from parent context applies here
return sendResponse(ctx, data)
}---
Checking Cancellation
In Long-Running Loops
func LongRunningOperation(ctx context.Context) error {
for {
select {
case <-ctx.Done():
return ctx.Err()
default:
// Do work
}
}
}Before Expensive Operations
Check cancellation before starting work that can't be interrupted:
func ProcessItems(ctx context.Context, items []Item) error {
for _, item := range items {
if ctx.Err() != nil {
return ctx.Err()
}
if err := expensiveProcess(item); err != nil {
return err
}
}
return nil
}Distinguishing Cancellation Causes
if err := ctx.Err(); err != nil {
switch {
case errors.Is(err, context.Canceled):
// Caller explicitly cancelled (e.g., client disconnected)
case errors.Is(err, context.DeadlineExceeded):
// Timeout or deadline passed
}
}---
Respecting Cancellation in HTTP Handlers
func handler(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
result, err := slowOperation(ctx)
if err != nil {
if errors.Is(err, context.Canceled) {
// Client disconnected — nothing to write
return
}
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
json.NewEncoder(w).Encode(result)
}The r.Context() is cancelled when:
- The client closes the connection
- The request is cancelled by the client or HTTP/2 transport
- The
ServeHTTPmethod returns
---
Context Value Best Practices
Use Unexported Key Types
type contextKey struct{}
var userIDKey contextKey
func WithUserID(ctx context.Context, id string) context.Context {
return context.WithValue(ctx, userIDKey, id)
}
func UserIDFromContext(ctx context.Context) (string, bool) {
id, ok := ctx.Value(userIDKey).(string)
return id, ok
}Using an unexported struct type as the key prevents collisions with keys from other packages — even if they use the same string or int value.
Provide Accessor Functions
Always wrap context.WithValue and ctx.Value in typed helper functions (as shown above) rather than exposing keys. This gives you type safety and a single place to change the implementation.
---
Quick Reference
| Pattern | Guidance |
|---|---|
| Parameter position | Always first: func F(ctx context.Context, ...) |
| Struct storage | Don't store in structs; pass to methods |
| Custom types | Don't create; use context.Context interface |
| Application data | Prefer parameters > receiver > globals > context values |
| Request-scoped data | Appropriate for context values |
| Sharing context | Safe — contexts are immutable |
context.Background() | Only for non-request-specific code |
| Default | Pass context even if you think you don't need it |
defer cancel() | Always defer immediately after WithTimeout/WithCancel/WithDeadline |
| Value keys | Use unexported struct types, provide accessor functions |
| Cancellation check | ctx.Err() before expensive ops; select on ctx.Done() in loops |
Related skills
How it compares
Pick go-context for context.Context placement and cancellation; use go-concurrency for goroutine lifecycle and sync primitives.
FAQ
Where should context.Context appear in Go function signatures?
go-context requires context.Context as the first parameter in any Go function that uses it, following the Go Wiki CodeReviewComments convention for services, APIs, and long-running operations.
What Go version does go-context require?
go-context requires Go 1.7 or later because context moved into the Go standard library in Go 1.7, replacing the experimental golang.org/x/net/context package.
Is Go Context safe to install?
skills.sh reports 3 of 3 security scanners passed. Review the Security Audits panel on this page before installing in production.