Loading...
Loading...
Compare original and translation side by side
Community default. A company skill that explicitly supersedesskill takes precedence.samber/cc-skills-golang@golang-context
社区默认规范。若存在明确替代的企业技能,以该企业技能为准。samber/cc-skills-golang@golang-context
context.Contextcontext.Contextctxctx context.Contextnilcontext.TODO()cancel()WithCancelWithTimeoutWithDeadlinecontext.Background()context.TODO()context.Background()context.WithoutCancelctxctx context.Contextnilcontext.TODO()WithCancelWithTimeoutWithDeadlinecancel()context.Background()context.TODO()context.Background()context.WithoutCancel| Situation | Use |
|---|---|
| Entry point (main, init, test) | |
| Function needs context but caller doesn't provide one yet | |
| Inside an HTTP handler | |
| Need cancellation control | |
| Need a deadline/timeout | |
| 场景 | 使用方法 |
|---|---|
| 入口点(main、init、测试) | |
| 函数需要上下文但调用方尚未提供 | |
| HTTP处理器内部 | |
| 需要手动控制取消 | |
| 需要设置超时/截止时间 | |
// ✗ 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)
}// ✗ 错误示例——创建新上下文,打断调用链
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)
}WithCancelWithTimeoutWithDeadline<-ctx.Done()AfterFuncWithoutCancelr.Context()NewRequestWithContext*ContextQueryContextExecContextWithCancelWithTimeoutWithDeadline<-ctx.Done()AfterFuncWithoutCancelr.Context()NewRequestWithContext*ContextQueryContextExecContextsamber/cc-skills-golang@golang-concurrencysamber/cc-skills-golang@golang-databasesamber/cc-skills-golang@golang-observabilitysamber/cc-skills-golang@golang-design-patternssamber/cc-skills-golang@golang-concurrencysamber/cc-skills-golang@golang-databasesamber/cc-skills-golang@golang-observabilitysamber/cc-skills-golang@golang-design-patternsgovetstaticchecksamber/cc-skills-golang@golang-lintergovetstaticchecksamber/cc-skills-golang@golang-linter