liveBook · Manning

Context

As explained in 100 Go Mistakes and How to Avoid Them

context.Context is the Go interface defining methods for retrieving deadlines, cancellation state, and propagated values.

A Go context carries a deadline, a cancellation signal, and values across API boundaries. Passing one to concurrent work lets that work respond when it should stop; it does not stop the work automatically. section 8.6 section 8.6.4

type Context interface {
    Deadline() (deadline time.Time, ok bool)
    Done() <-chan struct{}
    Err() error
    Value(key any) any
}

The interface exposes the deadline, cancellation notification, cancellation error, and propagated values. section 9.1

Done returns a receive-only channel that closes when cancellation or a deadline occurs. Closing the channel notifies all consumers. Before it closes, Err returns nil; afterward, Err reports the reason, such as context.Canceled or context.DeadlineExceeded. section 8.6.4

Cancel a file watcher

Create a context with context.WithCancel(context.Background()), pass it to the watcher goroutine, and defer the returned cancel function. The watcher can respond to cancellation by closing its file descriptor. Cancellation signals the watcher; it does not itself wait for cleanup to finish. section 8.6.2

func f(ctx context.Context) error {
    // ...
    select {              #1
    case <-ctx.Done():
        return ctx.Err()
    case ch1 <- struct{}{}:
    }
 
    select {              #2
    case <-ctx.Done():
        return ctx.Err()
    case v := <-ch2:
        // ...
    }
}

A context-aware function can select between each channel operation and ctx.Done(). A plain blocking send or receive could otherwise keep waiting after cancellation. section 8.6.4

func handler(w http.ResponseWriter, r *http.Request) {
    response, err := doSomeTask(r.Context(), r)         #1
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }
 
    go func() {                                         #2
        err := publish(r.Context(), response)
        // Do something with err
    }()
 
    writeResponse(response)                             #3
}

This handler passes the request context to an asynchronous publish. If the response is written first, the request context can be canceled before or during publication. section 9.1

Choose a context whose lifetime matches the work. Publishing with context.Background() avoids request cancellation but also discards request values. A wrapper can retain those values while exposing no deadline or cancellation; detached work still needs a plan to stop eventually. section 9.1 section 9.15

type detach struct {                  #1
    ctx context.Context
}
 
func (d detach) Deadline() (time.Time, bool) {
    return time.Time{}, false
}
 
func (d detach) Done() <-chan struct{} {
    return nil
}
 
func (d detach) Err() error {
    return nil
}
 
func (d detach) Value(key any) any {
    return d.ctx.Value(key)           #2
}

This wrapper delegates Value to the original context but removes its deadline and cancellation signal. section 9.1

How 100 Go Mistakes and How to Avoid Them covers it

How deep it goes
Explains the interface and cancellation notification, then works through cancellation-aware channel operations and context-lifetime mistakes.
Examples
Uses a file watcher and asynchronous HTTP-to-Kafka publishing to illustrate cancellation and context lifetime.
What you can do after
Diagnose context-lifetime bugs and apply cancellation-aware channel operations using Go's context package.
How it connects
Connects cancellation to channels, select, goroutines, and HTTP request lifetimes.

Also explained in

Compare how 7 books explain context →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Go Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.