Context
Using context cancellation and deadlines to stop work across a call chain.
context.Context is a value passed to functions to carry a stop signal, an optional deadline, the latest time work may continue, and request information. A request is one operation, such as a web page asking a server for data. Context lets the caller stop work when that operation ends or takes too long.
Accept context as the first parameter by convention. A timeout cancels the context automatically. defer schedules the cancel function to run when this function returns, which releases resources when work finishes early:
package main
import (
"context"
"fmt"
"time"
)
func fetch(ctx context.Context) error {
select {
case <-time.After(time.Second):
return nil
case <-ctx.Done():
return ctx.Err()
}
}
func main() {
ctx, cancel := context.WithTimeout(
context.Background(), 100*time.Millisecond,
)
defer cancel()
fmt.Println(fetch(ctx)) // context deadline exceeded
}In production
Pass context as the first parameter and pass it on to functions that do the work. Do not save a request's context in a long-lived struct. Give network and database calls a deadline, and check ctx.Done() inside long loops so they can stop early.