Loading...
Loading...
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.
npx skill4agent add samber/cc-skills-golang golang-contextCommunity default. A company skill that explicitly supersedesskill takes precedence.samber/cc-skills-golang@golang-context
context.Contextctxctx context.Contextnilcontext.TODO()cancel()WithCancelWithTimeoutWithDeadlinecontext.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 | |
// ✗ 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)
}WithCancelWithTimeoutWithDeadline<-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-patternsgovetstaticchecksamber/cc-skills-golang@golang-linter