golang-context by samber/cc-skills-golang
npx skills add https://github.com/samber/cc-skills-golang --skill golang-context社区默认值。 明确覆盖
samber/cc-skills-golang@golang-context技能的公司技能具有优先权。
context.Context 是 Go 用于在 API 边界之间和 goroutine 之间传播取消信号、截止时间和请求范围值的机制。可以将其视为请求的“会话”——它将属于同一工作单元的每个操作联系在一起。
ctx 必须是第一个参数,命名为 ctx context.Contextnil 上下文——如果不确定,使用 context.TODO()cancel() 在 // 之后立即延迟调用广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
WithCancelWithTimeoutWithDeadlinecontext.Background() 必须仅在最顶层(main、init、测试)使用context.TODO() 作为占位符,当你知道需要上下文但还没有时context.Background()context.WithoutCancel(Go 1.21+)当生成必须比父请求生命周期更长的后台工作时| 场景 | 使用 |
|---|---|
| 入口点(main、init、测试) | context.Background() |
| 函数需要上下文但调用者尚未提供 | context.TODO() |
| 在 HTTP 处理程序内部 | r.Context() |
| 需要取消控制 | context.WithCancel(parentCtx) |
| 需要一个截止时间/超时 | context.WithTimeout(parentCtx, duration) |
最重要的规则:在整个调用链中传播相同的上下文。当你正确传播时,取消父上下文会自动取消所有下游工作。
// ✗ 错误 — 创建新的上下文,破坏了链
func (s *OrderService) Create(ctx context.Context, order Order) error {
return s.db.ExecContext(context.Background(), "INSERT INTO orders ...", order.ID)
}
// ✓ 正确 — 传播调用者的上下文
func (s *OrderService) Create(ctx context.Context, order Order) error {
return s.db.ExecContext(ctx, "INSERT INTO orders ...", order.ID)
}
取消、超时和截止时间 — 取消如何传播:WithCancel 用于手动取消,WithTimeout 用于在一段时间后自动取消,WithDeadline 用于绝对时间截止。在并发代码中监听(<-ctx.Done())的模式、AfterFunc 回调,以及用于必须比其父请求生命周期更长的操作(例如,审计日志)的 WithoutCancel。
上下文值和跨服务追踪 — 安全的上下文值模式:使用未导出的键类型以防止命名空间冲突,何时使用上下文值(请求 ID、用户 ID)与函数参数。追踪上下文传播:OpenTelemetry 追踪头、用于日志聚合的相关 ID,以及跨服务边界编组/解编组上下文。
HTTP 服务器和服务调用中的上下文 — HTTP 处理程序上下文:r.Context() 用于请求范围的取消、中间件集成以及传播到服务。HTTP 客户端模式:NewRequestWithContext、客户端超时以及具有上下文感知的重试。数据库操作:始终使用 *Context 变体(QueryContext、ExecContext)以遵守截止时间。
samber/cc-skills-golang@golang-concurrency 技能,了解使用上下文的 goroutine 取消模式samber/cc-skills-golang@golang-database 技能,了解具有上下文感知的数据库操作(QueryContext、ExecContext)samber/cc-skills-golang@golang-observability 技能,了解使用 OpenTelemetry 的追踪上下文传播samber/cc-skills-golang@golang-design-patterns 技能,了解超时和弹性模式许多上下文陷阱可以通过 linter 自动捕获:govet、staticcheck。→ 参见 samber/cc-skills-golang@golang-linter 技能了解配置和用法。
每周安装次数
99
代码仓库
GitHub 星标数
184
首次出现
3 天前
安全审计
已安装于
opencode82
codex81
gemini-cli81
kimi-cli80
github-copilot80
amp80
Community default. A company skill that explicitly supersedes
samber/cc-skills-golang@golang-contextskill takes precedence.
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.
ctx MUST be the first parameter, named ctx context.Contextnil context — use context.TODO() if unsurecancel() MUST always be deferred immediately after WithCancel/WithTimeout/WithDeadlinecontext.Background() MUST only be used at the top level (main, init, tests)context.TODO() as a placeholder when you know a context is needed but don't have one yetcontext.Background() in the middle of a request pathcontext.WithoutCancel (Go 1.21+) when spawning background work that must outlive the parent request| 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) |
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)
}
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.
— HTTP handler context: for request-scoped cancellation, middleware integration, and propagating to services. HTTP client patterns: , client timeouts, and retries with context awareness. Database operations: always use variants (, ) to respect deadlines.
samber/cc-skills-golang@golang-concurrency skill for goroutine cancellation patterns using contextsamber/cc-skills-golang@golang-database skill for context-aware database operations (QueryContext, ExecContext)samber/cc-skills-golang@golang-observability skill for trace context propagation with OpenTelemetrysamber/cc-skills-golang@golang-design-patterns skill for timeout and resilience patternsMany context pitfalls are caught automatically by linters: govet, staticcheck. → See the samber/cc-skills-golang@golang-linter skill for configuration and usage.
Weekly Installs
99
Repository
GitHub Stars
184
First Seen
3 days ago
Security Audits
Gen Agent Trust HubPassSocketPassSnykPass
Installed on
opencode82
codex81
gemini-cli81
kimi-cli80
github-copilot80
amp80
React 组合模式指南:Vercel 组件架构最佳实践,提升代码可维护性
116,600 周安装
blu CLI 命令行工具:控制 Bluesound/NAD 播放器,实现音频设备自动化管理
2 周安装
Claude代码插件MCP集成指南:连接外部服务与API的完整教程
3 周安装
Sheetsmith - 轻量级 CSV/Excel 数据处理工具,pandas 封装,支持预览、筛选、转换
3 周安装
Trello API 集成指南:在 Moltbot 中管理看板、列表和卡片的完整教程
3 周安装
Things 3 命令行工具 - 在终端管理 macOS 待办事项,支持读写 Things 数据库
3 周安装
skill-creator 技能创建指南 - 高效构建AI技能模块与工具集成
3 周安装
r.Context()NewRequestWithContext*ContextQueryContextExecContext