Generated banner for Golang Context
Generated logo for Golang Context

Golang Context

Samuel BertheCommunityCreated by samberDistributed by Samuel Berthe

  • Skill
  • Guidelines
  • Software development
  • MIT
  • No issues found

From the author

Idiomatic context.Context usage in Golang — propagation through API boundaries, cancellation, timeouts and deadlines, request-scoped values, context.WithoutCancel for background work outliving requests. Apply when designing context propagation across layers, debugging leaked or unexpired contexts, choosing between context.Background/TODO/WithoutCancel, or storing values in context. Not for code that merely accepts ctx as first parameter.
— the description by samber

AutoGineer summary

Written by AutoGineer from the skill’s own files, not by the author

This skill provides a comprehensive guide to using context.Context in Go applications. It covers the essential patterns for propagating cancellation signals, deadlines, and request-scoped values across API boundaries. It emphasizes the importance of maintaining a consistent context chain throughout the request lifecycle, proper resource management with cancel functions, and the correct use of context-aware APIs for HTTP and database operations.

What it does

  • Defines patterns for propagating context through the entire request lifecycle.
  • Explains how to manage cancellation, timeouts, and deadlines using context.
  • Provides guidelines for storing and retrieving request-scoped values safely.
  • Outlines the correct usage of context.Background, context.TODO, and context.WithoutCancel.
  • Demonstrates how to integrate context into HTTP servers and downstream service calls.
  • Highlights common pitfalls like context leaks and improper context creation.

When to use it

  • When designing or refactoring context propagation across application layers.
  • When debugging issues related to leaked contexts or unexpired deadlines.
  • When implementing background tasks that need to outlive the parent request.
  • When creating middleware that requires request-scoped metadata.
  • When ensuring database or HTTP client operations respect request cancellation.

Advantages

  • Ensures consistent cancellation behavior across complex call chains.
  • Prevents resource leaks by enforcing proper deferral of cancel functions.
  • Improves code maintainability through idiomatic context handling.
  • Reduces bugs related to context-aware API misuse.
  • Facilitates better observability through standardized trace context propagation.

Usage examples

“How should I pass a context to a database query in a service method?”
The agent will demonstrate using the context passed as the first parameter to the service method and passing it directly into the database's QueryContext or ExecContext method.
“I need to spawn a background task that shouldn't be cancelled when the HTTP request finishes. How do I do that?”
The agent will explain how to use context.WithoutCancel to detach the background task from the request's context while preserving other necessary values.
“What is the best way to store a user ID in a context?”
The agent will provide an example of defining an unexported custom type for the context key to prevent collisions and using context.WithValue to store the data.
“Why is my application leaking resources when using context.WithTimeout?”
The agent will identify the missing defer cancel() call and explain why it is necessary to release timer resources.

Install

  1. Download the skill as a ZIP:

    https://autogineer.com/agent-skills/samber/golang-context/download
  2. Unzip it into the cross-client skills folder of your project:

    mkdir -p .agents/skills && unzip golang-context.zip -d .agents/skills

Documentation by samber

Community default. A company skill that explicitly supersedes samber/cc-skills-golang@golang-context skill takes precedence.

Go context.Context Best Practices

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.

Best Practices Summary

  1. Propagate the same context through the entire request lifecycle: HTTP handler → service → DB → external APIs — any link that starts a fresh context keeps working after the client is gone.

  2. Take ctx as the first parameter, named ctx context.Context — the fixed position is what makes context-aware APIs recognizable at a glance and what linters check.

  3. Pass context through function parameters instead of storing it in a struct — the struct outlives the request that filled it, so later calls reuse a context that is already cancelled or belongs to someone else.

  4. Pass context.TODO() rather than a nil context — nil panics on the first Done() or Value() call, far from the caller that passed it.

  5. Call cancel() on all control-flow paths for WithCancel/WithTimeout/WithDeadline, unless ownership of the context and cancel function is explicitly returned or transferred — an uncalled cancel() keeps the child attached to its parent and leaks its timer until the parent finishes.

  6. Create context.Background() only at top-level entry points (main, init, tests). Deeper in the call chain — especially mid-request — it detaches the work from the caller's deadline and cancellation, the propagation break shown below.

  7. Use context.TODO() as a placeholder when a context is needed but none exists yet — it marks the gap for a later fix instead of hiding it behind a Background() that looks deliberate.

  8. Declare context value keys as unexported types — with a plain string key, two packages using "user" silently overwrite each other.

  9. Carry only request-scoped metadata in context values, never function parameters — values retrieved through Value() lose compile-time typing and disappear from the function signature.

  10. Use context.WithoutCancel (Go 1.21+) when spawning background work that must outlive the parent request — otherwise the handler returning cancels the audit log or cleanup just started.

Creating Contexts

SituationUse
Entry point (main, init, test)context.Background()
Function needs context but caller doesn't provide one yetcontext.TODO()
Inside an HTTP handlerr.Context()
Need cancellation controlcontext.WithCancel(parentCtx)
Need a deadline/timeoutcontext.WithTimeout(parentCtx, duration)

Context Propagation: The Core Principle

The 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.

// ✗ Bad — creates a new context, breaking the chain
func (s *OrderService) Create(ctx context.Context, order Order) error {
    return s.db.ExecContext(context.Background(), "INSERT INTO orders ...", order.ID)
}

// ✓ Good — propagates the caller's context
func (s *OrderService) Create(ctx context.Context, order Order) error {
    return s.db.ExecContext(ctx, "INSERT INTO orders ...", order.ID)
}

Deep Dives

  • Cancellation, Timeouts & Deadlines — 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).

  • Context Values & Cross-Service Tracing — 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.

  • Context in HTTP Servers & Service Calls — 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.

Cross-References

  • → See the samber/cc-skills-golang@golang-concurrency skill for goroutine cancellation patterns using context

  • → See the samber/cc-skills-golang@golang-database skill for context-aware database operations (QueryContext, ExecContext)

  • → See the samber/cc-skills-golang@golang-observability skill for trace context propagation with OpenTelemetry

  • → See the samber/cc-skills-golang@golang-design-patterns skill for timeout and resilience patterns

Enforce with Linters

Many context pitfalls are caught automatically by linters: govet, staticcheck. → See the samber/cc-skills-golang@golang-lint skill for configuration and usage.

Files

references/http-services.md

Context in HTTP Servers & Service Calls

Table of Contents

  • Context in HTTP Servers

  • Middleware enriching context

  • Context in Calls to Other Services

Context in HTTP Servers

http.Request carries a context that is cancelled when the client disconnects or the request handler returns. MUST use r.Context() — NEVER create a new context.Background() inside a handler.

func (h *Handler) GetOrder(w http.ResponseWriter, r *http.Request) {
    ctx := r.Context() // this context is cancelled if the client disconnects

    order, err := h.orderService.Get(ctx, r.PathValue("id"))
    if err != nil {
        if ctx.Err() != nil {
            // Client disconnected, no point writing a response
            return
        }
        http.Error(w, "internal error", http.StatusInternalServerError)
        return
    }

    json.NewEncoder(w).Encode(order)
}

Middleware enriching context

Middleware injects request-scoped values before handlers run. Use unexported key types to prevent collisions:

// Helpers for trace propagation
type contextKey string
const (
    traceIDKey contextKey = "trace_id"
    spanIDKey  contextKey = "span_id"
)

func TracingMiddleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        traceID := r.Header.Get("X-Trace-ID")
        if traceID == "" {
            traceID = generateTraceID()
        }
        spanID := r.Header.Get("X-Span-ID")
        if spanID == "" {
            spanID = generateSpanID()
        }

        ctx := context.WithValue(r.Context(), traceIDKey, traceID)
        ctx = context.WithValue(ctx, spanIDKey, spanID)

        w.Header().Set("X-Trace-ID", traceID)
        w.Header().Set("X-Span-ID", spanID)
        next.ServeHTTP(w, r.WithContext(ctx))
    })
}

// Propagate trace context to downstream services
func (c *HTTPClient) Do(ctx context.Context, method, url string, body io.Reader) (*http.Response, error) {
    req, err := http.NewRequestWithContext(ctx, method, url, body)
    if err != nil {
        return nil, fmt.Errorf("creating request: %w", err)
    }

    if traceID, ok := ctx.Value(traceIDKey).(string); ok {
        req.Header.Set("X-Trace-ID", traceID)
    }
    if spanID, ok := ctx.Value(spanIDKey).(string); ok {
        req.Header.Set("X-Span-ID", spanID)
    }
    return c.client.Do(req)
}

Context in Calls to Other Services

Context MUST be propagated to all HTTP clients and databases using context-aware APIs: http.NewRequestWithContext, QueryContext, ExecContext, and QueryRowContext. This ensures that client disconnections cancel all downstream operations.

// ✗ Bad — downstream calls ignore the request context
func (c *PaymentClient) Charge(ctx context.Context, amount int) error {
    req, _ := http.NewRequest("POST", c.url+"/charge", body)
    return c.client.Do(req) // not context-aware
}

// ✓ Good — all downstream operations respect the context
func (c *PaymentClient) Charge(ctx context.Context, amount int) error {
    req, err := http.NewRequestWithContext(ctx, "POST", c.url+"/charge", body)
    if err != nil {
        return fmt.Errorf("creating request: %w", err)
    }
    return c.client.Do(req)
}
// ✗ Bad — downstream calls ignore the request context
func (r *UserRepo) FindByID(ctx context.Context, id string) (*User, error) {
    row := r.db.QueryRow("SELECT * FROM users WHERE id = $1", id)
    // ...
}

// ✓ Good — all downstream operations respect the context
func (r *UserRepo) FindByID(ctx context.Context, id string) (*User, error) {
    row := r.db.QueryRowContext(ctx, "SELECT * FROM users WHERE id = $1", id)
    // ...
}

Requirements and compatibility

Written for: Claude Code, OpenAI Codex

Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta

“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.

Needs: Declares allowed tools, Claude Code frontmatter

The author says: Designed for Claude Code, Codex or similar harness, and for projects using Golang.

Security

No issues found by our static scan· No issues found

A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.

Attribution and licence

Created by
samber
Publisher
Samuel Berthe (Community)
Distributed by
Samuel Berthe
Source
samber/cc-skills-golang · skills/golang-context · commit bb1d43d
Licence
MIT License (redistribution allowed)
  • LICENSE (added by AutoGineer from LICENSE)
  • ATTRIBUTION.md (written by AutoGineer)
Synced

AutoGineer is not affiliated with or endorsed by samber or Samuel Berthe.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download golang-context.zip