Module lessons (5/5)
`context.Context`: cancellation and deadline
Propagate deletion between goroutine, context.WithTimeout, ctx.Done(), the first parameter pattern.
What you'll learn in this lesson
- Propagate cancellation signals and deadlines (
deadline/timeout) along concurrent call trees viacontext.Context. - Always respect the canonical signature
ctx context.Contextas the first parameter and calldefer cancel(). - Distinguish
context.Background(),context.TODO()and usecontext.WithValueonly for request-scoped metadata with typed private keys.
Overview
In real applications (HTTP servers, gRPC clients, CLI workers), when a user cancels a request or a network timeout expires, all derivative work must quickly stop: this is the central role of context.Context.
Throughout the Go ecosystem, ctx context.Context is strictly the first parameter of functions and methods: it should never be hidden inside a long-lived struct nor passed as nil. On HTTP servers, r.Context() is automatically deleted if the client closes the connection:
Sections covered in this lesson
- 1Create roots and contexts with clearing/timeout
- 2First parameter convention and HTTP propagation
- 3
context.WithValue: Only per-request metadata with key not exported - 4Respect
<-ctx.Done()in blocking functions - 5Guided practice
- 6Check for understanding
Unlock "`context.Context`: cancellation and deadline" and the full Course Go curriculum
Propagate deletion between goroutine, `context.WithTimeout`, `ctx.Done()`, the first parameter pattern.
Unlock all 5 hands-on exercises in this lesson plus every advanced WebAssembly module with automated checks.
- Instant access to all advanced modules in Course Go plus 17 more courses
- Hands-on browser exercises with automated test suites and solutions
- 14-day money-back guarantee processed via Paddle.com
14-day guarantee · Cancel anytimeModule 1, all 18 interactive games, and cheatsheets are always free.