Junior — Middle
Have you dealt with using the WithTimeout context in your projects?
sobes.tech AI
Answer from AI
Yes, in Go projects, it is common to use a context with a timeout (context.WithTimeout) to control the execution time of operations, especially when working with network requests, databases, or other long-running processes.
The principle: a new context is created that automatically cancels after the specified time. This helps prevent hangs and resource leaks.
Example:
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
select {
case <-time-consuming-operation(ctx):
fmt.Println("Operation completed")
case <-ctx.Done():
fmt.Println("Timeout reached, operation cancelled")
}
Thus, WithTimeout helps manage execution time and handle cases where an operation takes too long.