What types of context do you know?
sobes.tech AI
Answer from AI
In Go, the context.Context is used to pass cancellation signals, deadlines, and values between goroutines and functions.
Main types of context:
-
Background — the base context, usually used as the root when starting an application or goroutine.
-
TODO — used when the context is not yet defined or will be added later.
-
With cancellation (
WithCancel) — allows canceling operations when the cancel function is called. -
With deadline (
WithDeadline) — automatically cancels after a specified time. -
With timeout (
WithTimeout) — a simplified version with a deadline, where a wait time is set. -
With value (
WithValue) — allows passing data (e.g., request IDs) through call chains.
Example of creating a context with a timeout:
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
// use ctx in requests or goroutines
Context helps manage the lifetime of operations and cancel them if necessary, which is important for writing reliable and responsive code.