Why context.Context Exists
Cancellation and request lifecycle management
The problem
Without a mechanism to cancel in-flight work, a slow database query or HTTP call blocks its goroutine until it completes, wasting resources when the original request was already abandoned.
context.Context overview
context.Context is an interface that carries a cancellation signal, an optional deadline, and key-value metadata across API boundaries and goroutines.
type Context interface {
Deadline() (deadline time.Time, ok bool)
Done() <-chan struct{}
Err() error
Value(key any) any
}All lessons in this course
- Why context.Context Exists
- WithCancel and WithTimeout
- WithDeadline and WithValue
- Context in HTTP and Database Calls