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






