Middle+
What is context in Go and what is it used for?
sobes.tech AI
Answer from AI
In Go, context is a package that provides the Context type used for passing cancellation signals, deadlines, and other important values between goroutines.
Main purposes of context:
- Managing the lifetime of operations (e.g., canceling a request on timeout).
- Passing metadata (e.g., request identifiers for logging).
- Synchronizing cancellation of multiple related operations.
Example of usage:
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
defer cancel()
select {
case <-time.After(time.Second * 10):
fmt.Println("operation completed")
case <-ctx.Done():
fmt.Println("operation cancelled or timed out")
}
Here, the context allows canceling the operation if it takes longer than 5 seconds.