Skip to main content
Module 7 · Lesson 5 of 535/50 in the course~14 min
Module lessons (5/5)

`context.Context`: cancellation and deadline

Lesson preview5 hands-on exercises readyCourse Go · Module 7 — Competition

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 via context.Context.
  • Always respect the canonical signature ctx context.Context as the first parameter and call defer cancel().
  • Distinguish context.Background(), context.TODO() and use context.WithValue only 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

  1. 1Create roots and contexts with clearing/timeout
  2. 2First parameter convention and HTTP propagation
  3. 3context.WithValue: Only per-request metadata with key not exported
  4. 4Respect <-ctx.Done() in blocking functions
  5. 5Guided practice
  6. 6Check for understanding
Pro Lesson · Module 7 — Competition

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.