context Flashcards
(10 cards)
1
Q
Context Basics
A
Purpose:
Carries deadlines, cancellation signals, and request-scoped values across API boundaries.
Creation:
ctx := context.Background() // Root context ctx = context.TODO() // Temporary placeholder
2
Q
Cancellation
A
WithCancel:
ctx, cancel := context.WithCancel(parentCtx) defer cancel() // Release resources go func() { <-ctx.Done() // Triggered on cancel() fmt.Println("Canceled:", ctx.Err()) // "context canceled" }() cancel() // Propagates cancellation
3
Q
Deadlines
A
WithDeadline:
deadline := time.Now().Add(2 * time.Second) ctx, cancel := context.WithDeadline(parentCtx, deadline) defer cancel() select { case <-time.After(3 * time.Second): fmt.Println("Work completed") case <-ctx.Done(): fmt.Println("Deadline exceeded:", ctx.Err()) // "context deadline exceeded" }
4
Q
Timeouts
A
WithTimeout:
ctx, cancel := context.WithTimeout(parentCtx, 100*time.Millisecond) defer cancel()
Equivalent to:
WithDeadline(parentCtx, time.Now().Add(100*time.Millisecond))
5
Q
Context Values
A
WithValue:
type key string ctx := context.WithValue(parentCtx, key("user"), "Alice") if val := ctx.Value(key("user")); val != nil { fmt.Println("User:", val) // "User: Alice" }
Key Rules:
1. Use custom types for keys (avoid string)
2. Values should be immutable
3. Don’t abuse for dependency injection
6
Q
Context in HTTP
A
Server:
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { ctx := r.Context() select { case <-time.After(5 * time.Second): w.Write([]byte("Done")) case <-ctx.Done(): fmt.Println("Request canceled") } })
Client:
req, _ := http.NewRequestWithContext(ctx, "GET", url, nil) client.Do(req) // Respects context cancellation
7
Q
Best Practices
A
- Propagate contexts through call chains
- Always call cancel() to avoid leaks
- Prefer explicit timeout/deadline over Background()
- Never store mutable objects in values
- Context should be first parameter (convention)
8
Q
Error Handling
A
Check Errors:
<-ctx.Done() switch ctx.Err() { case context.Canceled: // Manual cancellation case context.DeadlineExceeded: // Timeout reached }
9
Q
Common Patterns
A
Database Query:
rows, err := db.QueryContext(ctx, "SELECT...") if errors.Is(err, context.Canceled) { // Handle cancellation }
gRPC:
resp, err := client.SomeRPC(ctx, request)
10
Q
Anti-Patterns
A
❌ Storing contexts in structs
❌ Using for non-request-scoped data
❌ Ignoring ctx.Done() in long-running ops
❌ Mixing cancellation signals