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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
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"
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
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))
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Best Practices

A
  1. Propagate contexts through call chains
  2. Always call cancel() to avoid leaks
  3. Prefer explicit timeout/deadline over Background()
  4. Never store mutable objects in values
  5. Context should be first parameter (convention)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Error Handling

A

Check Errors:

<-ctx.Done()
switch ctx.Err() {
case context.Canceled:
    // Manual cancellation
case context.DeadlineExceeded:
    // Timeout reached
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
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)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly