• English
  • 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 exposing Done() (cancellation channel), Err() (reason for cancellation), Deadline(), and Value().
    • **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 a cancel() function. Calling cancel() signals all child goroutines listening to ctx.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 when cancel() 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.Context as 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 WithValue for optional function parameters or core business logic; reserve it exclusively for request-scoped metadata.