Freebie

Context

  • Need to propogate cancellation signals to stop ongoing operations when they’re no longer needed, such as when users cancel requests of there is a timeout.

Basics

Context is an idiomatic way to propagate cancellation signals through an app. It is like a tree, with a root context, branches, and leaves. A cancellation propagates through the hierarchy. If you cancel a parent, all children contexts are cancelled. However, if you cancel a child context, the parent context is untouched.

A root Context is immutable—you can’t cancel it—but you can derive a cancellable Context from it. For example:

  1. Gets a root context.

  2. Creates a cancellable context from root. WithTimeout takes a parent context and a time.Duration timeout. This context cancels automatically after 15 seconds.

    root := context.Background()                                         // 1
    child, cancel := context.WithTimeout(root, 15*time.Second)           // 2
    grandChild, cancel := context.WithTimeout(root, 5*time.Second)       // 3
    

Create a context

This table summarizes the ways to create a context:

FunctionCreatesUsageAuto-Cancels?Cancel Func?
context.Background()Root contextIn main, app startup, testsNoNo
context.TODO()Placeholder rootWhen refactoring or undecidedNoNo
context.WithCancel(parent)Cancelable childManual cancellation (goroutines, shutdown)No (manual only)Yes
context.WithTimeout(parent, d)Child with timeoutLimit operation durationYes (after duration)Yes
context.WithDeadline(parent, t)Child with deadlineCancel at specific timeYes (at deadline)Yes
context.WithValue(parent, key, val)Child with valueRequest-scoped metadataNoNo

Context methods

MethodReturnsDescriptionUsage
ctx.Done()<-chan struct{}Closes when canceled or expiredIn select to stop work
ctx.Err()errorWhy it was canceledAfter Done() fires
ctx.Deadline()(time.Time, bool)Reports deadline if setRare — mostly internal libs
ctx.Value(key)anyGets stored valueRequest metadata

Context in practice

  • Passes as the first parameter for consistency