Understand the contract
context.Context carries cancellation, deadlines and request-scoped values across API boundaries. Pass it as the first parameter to operations that may block. Cancellation is cooperative: code must observe ctx.Done or call APIs that honor the context. Canceling does not forcibly terminate a goroutine.
WithCancel returns a derived context and a cancel function. Call cancel when the operation is finished to release associated resources. WithTimeout adds a deadline and still needs cancellation cleanup. Avoid storing contexts in long-lived structs or using context values as a general configuration container.
Work through the example
The example deliberately cancels before calling wait so its output is deterministic. wait immediately observes the closed Done channel and returns context.Canceled. In a real worker, select would often include both a work channel and ctx.Done so idle waiting can be interrupted.
package main
import (
"context"
"fmt"
)
func wait(ctx context.Context) error {
<-ctx.Done()
return ctx.Err()
}
func main() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
cancel()
fmt.Println(wait(ctx))
}Watch this boundary
Canceling a context does not prove workers have exited. Combine cancellation with a WaitGroup or completion channel when shutdown requires that guarantee. Also check cancellation around blocking sends, not only before computing a result; a receiver may have left while the work was running.
Practice with a changed input
Use errors.Is to recognize context.Canceled. Then create a worker that waits on either a jobs channel or ctx.Done and signals completion before main returns.
Lesson 47 of 50
View the full Go basics seriesReferences & further reading
Need help with your Go backend?
I work with engineering teams on focused Go and Kubernetes platform engagements, with limited consulting availability.
Explore Go consulting services