AGENT SKILL

go-context

Use when handling Go context.Context, cancellation, deadlines, timeouts, or request-scoped values and parameter placement. Goroutine lifecycle and synchronization belong to go-concurrency.

License 许可
Apache-2.0
最近更新
2026-11-14
Stars
★ 7
Forks
2

01 前言 Front Matter

name
go-context
description
Use when handling Go context.Context, cancellation, deadlines, timeouts, or request-scoped values and parameter placement. Goroutine lifecycle and synchronization belong to go-concurrency.

02 资源文件 1

03 SKILL.md 正文

Go Context Usage

Compatibility: Baseline Go 1.27 (see COMPATIBILITY.md). context.WithoutCancel, context.AfterFunc, context.WithTimeoutCause and context.WithDeadlineCause require Go 1.21+; t.Context() in tests, Go 1.24+.

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 accept it as their first parameter. Do not add a Context member to a struct type (containedctx in the gate reports it); pass ctx to each method that needs it. Exception: methods whose signature must match an interface in the standard library or a third-party library. Do not create custom Context types or use interfaces other than context.Context in function signatures.


Where to Put Application Data

Parameters first, then the receiver, then a global; a context value carries only request-scoped data that crosses APIs — a request or trace ID, the authenticated principal — never an optional parameter, per-process configuration, or a deadline, which is derived with WithTimeout, WithDeadline, or WithCancel.


Common Patterns

Deriving Contexts

defer cancel() immediately after creating a derived context. Inside a loop a defer waits for the function to return, so every iteration's context stays live until then: cancel at the end of each iteration, or move the iteration into its own function that defers cancel().

ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()

for _, item := range items {
    itemCtx, cancelItem := context.WithTimeout(ctx, time.Second)
    err := send(itemCtx, item)
    cancelItem() // per iteration, not deferred
    if err != nil {
        return err
    }
}

Cancellation With a Reason

With context.WithCancelCause, WithTimeoutCause, or WithDeadlineCause, ctx.Err() still returns Canceled or DeadlineExceeded; only context.Cause(ctx) returns the reason supplied, so a caller that must tell this cancellation or timeout from an upstream one reads Cause. WithCancelCause returns a CancelCauseFunc, released on the success path with defer cancel(nil); WithTimeoutCause and WithDeadlineCause return a plain CancelFunc (defer cancel()), and their cause is set only when the timer fires.

context.WithoutCancel(ctx) keeps the values but drops cancellation; use it for work that must outlive the request (audit log, cleanup) and give that work its own timeout.


Related Skills

04 同仓库更多 Skills

h0rn3t
h0rn3t/golang-skills

go-troubleshooting

Use when investigating a bug or ticket in a Go service whose cause is unknown — wrong or missing results, tenant-specific behavior, a regression, stage/prod/CI differences, a panic, hang, deadlock, leak, unexplained CPU/RSS growth, or a flaky test. Also use for pasted stack traces, profiles, logs, or requests to find a Go issue's root cause, even without the word debug. Does not cover rewriting ticket text, implementing an already-diagnosed fix alone (use its topic skill), or optimizing a known bottleneck (see go-performance).

★ 7
h0rn3t
h0rn3t/golang-skills

go-testing

Use when writing, reviewing, or improving Go test code — including table-driven tests, subtests, parallel tests, test helpers, test doubles, and assertions with cmp.Diff. Also use when a user asks to write a test for a Go function, even if they don't mention specific patterns like table-driven tests or subtests. Does not cover benchmark performance testing (see go-performance).

★ 7
h0rn3t
h0rn3t/golang-skills

go-style-core

Use when resolving Go style or language mechanics such as formatting, nesting, declarations, initialization, scope, shadowing, loops, switches, or enum zero values. API design, naming, errors, and tests have specialized skills.

★ 7
h0rn3t
h0rn3t/golang-skills

go-security

Use when writing or reviewing Go code that touches untrusted input, secrets, or credentials — SQL, shell, or template injection, path traversal, SSRF, cookies and security headers, password hashing, TLS settings, token comparison, or what may appear in a log line. Also use when a handler accepts a file name, URL, or command argument from a client, or when asked to find "vulnerabilities", even if the user never says "security". Does not cover the os.Root and crypto/rand mechanics (see go-defensive) or the dependency CVE scan in the gate (see go-linting).

★ 7
h0rn3t
h0rn3t/golang-skills

go-resilience

Use when handling Go dependency failures or overload with retries, backoff/jitter, budgets, idempotency, duplicate delivery, circuit breakers, bulkheads, rate limits, backpressure, or degradation. Unknown root causes belong to go-troubleshooting.

★ 7
h0rn3t
h0rn3t/golang-skills

go-performance

Use when optimizing slow or performance-critical Go code, allocations, string concatenation in loops, or benchmarks. Also use when writing or reviewing a cache, including implementing one from a stub — its key, its expiry, and how a miss loads. Concurrent code patterns belong to go-concurrency.

★ 7