Middle
What is the context in Go? What is it used for? How does timeout cancellation work?
sobes.tech AI
Answer from AI
In Go, context is a package and a concept for managing the lifetime of operations, passing cancellation signals, and deadlines between goroutines.
Main tasks of context:
- cancel operations (e.g., on timeout or user cancellation),
- pass values (e.g., request ID) through call chains,
- set deadlines (timeouts).
Timeout cancellation works as follows:
- A context with a deadline or timeout is created, for example,
context.WithTimeout. - When the time expires, the context is automatically canceled.
- The goroutine listening to this context receives a cancellation signal through the
Done()channel. - The goroutine should handle cancellation properly (e.g., interrupt work and free resources).
Example:
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
select {
case <-time.After(3 * time.Second):
fmt.Println("operation completed")
case <-ctx.Done():
fmt.Println("operation cancelled or timed out")
}
Here, the operation will be interrupted after 2 seconds if it does not finish earlier.