In Go, context.Context carries deadlines, cancellation signals, and request-scoped values across API boundaries. Pass it as the first function parameter, conventionally named ctx, so downstream operations can respond to the same request lifecycle. section 10.6.1 section 10.6.2
The interface exposes four methods:
- Deadline reports when the context expires, if a deadline is set. section 10.6.1
- Done returns a channel that closes when the context ends; Err reports why it ended, or nil while it remains active. section 10.6.1
- Value retrieves a value by key. Use it for noncritical request or monitoring identifiers, not business inputs that should be explicit parameters. section 10.6.1
Create an application’s root context with context.Background in main, then pass it to dependencies. When a function receives a context, use it instead of creating a new root. Derive children with context.WithDeadline for a specific time or context.WithTimeout for a duration; avoid storing a context in a struct to save passing it. section 10.6.2
Give each remote call its own child context when you need to bound and distinguish its duration. Choose a timeout that accounts for network latency. A repository can accept a context even while its in-memory implementation ignores it, preparing the interface for a database that can respond to an interrupted call. section 10.6.3 section 10.3.3
Listing 10.30 create.go: Adding a context around the db call
// Create adds a habit into the DB.
func Create(ctx context.Context, db habitCreator, h Habit) (Habit, error) {
h, err := validateAndCompleteHabit(h)
if err != nil {
return Habit{}, err
}
dbCtx, cancel := context.WithTimeout(
ctx, 100*time.Millisecond) #1
defer cancel() #2
err = db.Add(dbCtx, h) #3
if err != nil {
return Habit{}, fmt.Errorf("cannot save habit: %w", err)
}
return h, nil
}
The habit creation function derives a 100 ms child context for the repository call and defers its cancellation. section 10.6.3
A timeout signals that work should stop; the operation must observe that signal. A select can wait for either a response or ctx.Done(), returning ctx.Err() when the context ends. section 10.6.3
Listing 10.32 create_test.go: Testing the timeout
func TestCreate(t *testing.T) {
// ...
"db timeout": {
db: func(ctl *minimock.Controller) *mocks.HabitCreatorMock {
db := mocks.NewHabitCreatorMock(ctl)
db.AddMock.Set(
func(ctx context.Context, habit habit.Habit) error {
select {
// This tick is longer than a database call
case <-time.Tick(2 * time.Second):
return nil
case <-ctx.Done():
return ctx.Err()
}
})
return db
},
expectedErr: context.DeadlineExceeded, #1
},
The timeout test uses a mock repository that waits for ctx.Done() and returns ctx.Err(), expecting context.DeadlineExceeded. section 10.6.3
A child context changes the argument passed to a mock. Minimock’s minimock.AnyContext can match it without requiring an exact deadline, but a separate test is needed to verify timeout behavior. section 10.6.3






