WithDeadline and WithValue
Absolute deadlines and passing request-scoped values
context.WithDeadline
WithDeadline creates a context that cancels at an absolute time. If the parent already has an earlier deadline, the parent deadline takes precedence.
deadline := time.Now().Add(10 * time.Second)
ctx, cancel := context.WithDeadline(parent, deadline)
defer cancel()WithTimeout vs WithDeadline
WithTimeout(parent, d) is equivalent to WithDeadline(parent, time.Now().Add(d)). Use WithDeadline when you have an absolute expiration (e.g., from an incoming RPC header).
All lessons in this course
- Why context.Context Exists
- WithCancel and WithTimeout
- WithDeadline and WithValue
- Context in HTTP and Database Calls