Principal
What is a context in Go?
sobes.tech AI
Answer from AI
In Go, context is a package and a concept used to pass information about request lifetime, cancel operations, and transfer values between goroutines.
Main tasks of context:
- Managing cancellation of operations (e.g., on timeout or user request cancellation).
- Passing deadlines (the time by which an operation should complete).
- Passing request-related values (e.g., identifiers, tokens).
Example of usage:
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
// Cancel after 5 seconds timeout
go func(ctx context.Context) {
select {
case <-time.After(time.Second * 10):
fmt.Println("operation completed")
case <-ctx.Done():
fmt.Println("operation cancelled or timed out")
}
}(ctx)
// Call cancel at the end to free resources
cancel()
Thus, context helps control the lifecycle of operations and coordinate work between goroutines.