Loading...
Loading...
Go context.Context usage patterns including parameter placement, avoiding struct embedding, and proper propagation. Use when working with context.Context in Go code for cancellation, deadlines, and request-scoped values.
npx skill4agent add cxuu/golang-skills go-contextcontext.ContextBased on Go Wiki CodeReviewComments - Contexts.
// Good: Context is first parameter
func F(ctx context.Context, /* other arguments */) error {
// ...
}
func ProcessRequest(ctx context.Context, req *Request) (*Response, error) {
// ...
}ctx// Bad: Context stored in struct
type Worker struct {
ctx context.Context // Don't do this
// ...
}
func (w *Worker) Process() error {
// Uses w.ctx - context lifetime unclear
}// Good: Context passed to methods
type Worker struct {
// ...
}
func (w *Worker) Process(ctx context.Context) error {
// Context explicitly passed - lifetime clear
}context.Context// Bad: Custom context type
type MyContext interface {
context.Context
GetUserID() string
}
func Process(ctx MyContext) error { ... }// Good: Use standard context.Context
func Process(ctx context.Context) error {
userID := GetUserID(ctx) // Extract from context value
// ...
}// Good: Explicit parameter
func ProcessOrder(ctx context.Context, userID string, order *Order) error {
// userID is explicit
}
// Good: Context value for request-scoped data
func ProcessOrder(ctx context.Context, order *Order) error {
// Request ID from context is appropriate - it's request-scoped
reqID := RequestIDFromContext(ctx)
// ...
}ctx// Good: Same context to multiple calls
func ProcessBatch(ctx context.Context, items []Item) error {
for _, item := range items {
// Safe to pass same ctx to each call
if err := process(ctx, item); err != nil {
return err
}
}
return nil
}
// Good: Same context to concurrent calls
func ProcessConcurrently(ctx context.Context, a, b *Data) error {
g, ctx := errgroup.WithContext(ctx)
g.Go(func() error { return processA(ctx, a) })
g.Go(func() error { return processB(ctx, b) })
return g.Wait()
}context.Background()// Good: Main function or initialization
func main() {
ctx := context.Background()
if err := run(ctx); err != nil {
log.Fatal(err)
}
}
// Good: Top-level background task
func startBackgroundWorker() {
ctx := context.Background()
go worker(ctx)
}context.Background()// Prefer: Accept context even for "simple" operations
func LoadConfig(ctx context.Context) (*Config, error) {
// Even if not using ctx now, accepting it allows future
// additions without API changes
}// Add timeout
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
// Add cancellation
ctx, cancel := context.WithCancel(ctx)
defer cancel()
// Add deadline
ctx, cancel := context.WithDeadline(ctx, time.Now().Add(time.Hour))
defer cancel()
// Add value (use sparingly)
ctx = context.WithValue(ctx, requestIDKey, reqID)func LongRunningOperation(ctx context.Context) error {
for {
select {
case <-ctx.Done():
return ctx.Err()
default:
// Do work
}
}
}func handler(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
result, err := slowOperation(ctx)
if err != nil {
if errors.Is(err, context.Canceled) {
// Client disconnected
return
}
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
json.NewEncoder(w).Encode(result)
}| Pattern | Guidance |
|---|---|
| Parameter position | Always first: |
| Struct storage | Don't store in structs; pass to methods |
| Custom types | Don't create; use |
| Application data | Prefer parameters > receiver > globals > context values |
| Request-scoped data | Appropriate for context values |
| Sharing context | Safe - contexts are immutable |
| Only for non-request-specific code |
| Default | Pass context even if you think you don't need it |