Go's 'context' Package
The Go context package provides a standardized way to carry deadlines, cancellation signals, and request-scoped values across API boundaries and between concurrent goroutines. It is essential for managing the lifecycle of requests in network servers, databases, and microservices.
Core Interfaces & Types:
context.Context: The core interface exposingDone()(cancellation channel),Err()(reason for cancellation),Deadline(), andValue().- **
context.Background()/context.TODO()**: Top-level, non-nil, empty contexts used as the root for context trees.
Key Constructors:
context.WithCancel(parent): Returns a child context and acancel()function. Callingcancel()signals all child goroutines listening toctx.Done()to terminate.- **
context.WithTimeout(parent, duration)/context.WithDeadline(parent, time)**: Automatically cancels the context when the elapsed time or explicit deadline is reached (or whencancel()is called explicitly). context.WithValue(parent, key, val): Attaches immutable, request-scoped key-value data (e.g., trace IDs, authentication tokens) passed along the call stack.
Best Practices:
- Pass as First Parameter: Idiomatically named
ctx ctx.Contextas the first parameter of functions performing I/O. - Always Call Cancel: Store and invoke
defer cancel()when using timeout or cancel contexts to prevent resource/goroutine leaks. - Keep Values Request-Scoped: Do not use
WithValuefor optional function parameters or core business logic; reserve it exclusively for request-scoped metadata.