返回顶部
g

golang-context

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.

作者: admin | 来源: ClawHub
源自
ClawHub
版本
V 1.1.1
安全检测
已通过
143
下载量
0
收藏
概述
安装方式
版本历史

golang-context

> **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. The same context MUST be propagated through the entire request lifecycle: HTTP handler → service → DB → external APIs 2. `ctx` MUST be the first parameter, named `ctx context.Context` 3. NEVER store context in a struct — pass explicitly through function parameters 4. NEVER pass `nil` context — use `context.TODO()` if unsure 5. `cancel()` MUST always be deferred immediately after `WithCancel`/`WithTimeout`/`WithDeadline` 6. `context.Background()` MUST only be used at the top level (main, init, tests) 7. **Use `context.TODO()`** as a placeholder when you know a context is needed but don't have one yet 8. NEVER create a new `context.Background()` in the middle of a request path 9. Context value keys MUST be unexported types to prevent collisions 10. Context values MUST only carry request-scoped metadata — NEVER function parameters 11. **Use `context.WithoutCancel`** (Go 1.21+) when spawning background work that must outlive the parent request ## Creating Contexts | Situation | Use | | --- | --- | | Entry point (main, init, test) | `context.Background()` | | Function needs context but caller doesn't provide one yet | `context.TODO()` | | Inside an HTTP handler | `r.Context()` | | Need cancellation control | `context.WithCancel(parentCtx)` | | Need a deadline/timeout | `context.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. ```go // ✗ 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](./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). - **[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. - **[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. ## 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-linter` skill for configuration and usage.

标签

skill ai

通过对话安装

该技能支持在以下平台通过对话安装:

OpenClaw WorkBuddy QClaw Kimi Claude

方式一:安装 SkillHub 和技能

帮我安装 SkillHub 和 golang-context-1776093722 技能

方式二:设置 SkillHub 为优先技能安装源

设置 SkillHub 为我的优先技能安装源,然后帮我安装 golang-context-1776093722 技能

通过命令行安装

skillhub install golang-context-1776093722

下载 Zip 包

⬇ 下载 golang-context v1.1.1

文件大小: 11.56 KB | 发布时间: 2026-4-14 11:19

v1.1.1 最新 2026-4-14 11:19
- Bumped skill version to 1.1.1 in metadata.
- No changes to guidelines, usage, or functionality—documentation only.

Archiver·手机版·闲社网·闲社论坛·羊毛社区· 多链控股集团有限公司 · 苏ICP备2025199260号-1

Powered by Discuz! X5.0   © 2024-2025 闲社网·线报更新论坛·羊毛分享社区·http://xianshe.com

p2p_official_large
返回顶部