0PricingLogin
Go Academy · Lesson

WithCancel and WithTimeout

Creating cancelable and timed contexts

context.WithCancel

WithCancel derives a new context with a cancel function. Calling cancel closes the Done channel of the derived context and all its children.

ctx, cancel := context.WithCancel(parent)
defer cancel() // always call to release resources
go doWork(ctx)

Always defer cancel

Failing to call cancel leaks the goroutine that monitors the parent context. Always defer cancel immediately after creating a cancellable context.

All lessons in this course

  1. Why context.Context Exists
  2. WithCancel and WithTimeout
  3. WithDeadline and WithValue
  4. Context in HTTP and Database Calls
← Back to Go Academy