Senior
What is the purpose of context? How have you used it in practice?
sobes.tech AI
Answer from AI
In Go, context is used to pass signals for cancellation, deadlines, and other values between goroutines, especially when working with requests, timeouts, and operation cancellations.
Practical applications:
- Cancel long-running operations when closing an HTTP request.
- Pass a deadline so that an operation does not run longer than the specified time.
- Pass metadata (e.g., request identifiers) through a chain of calls.
Example usage:
func handler(ctx context.Context) {
select {
case <-time.After(5 * time.Second):
fmt.Println("Operation completed")
case <-ctx.Done():
fmt.Println("Operation cancelled")
}
}
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
handler(ctx)
}
Here, the operation will be interrupted after 2 seconds, even if it is designed for 5 seconds.