Go
context
Control timeout and cancellation using context.
By EZ4Code Team
contexttimeout
Code
package main
import (
"context"
"fmt"
"time"
)
func operation(ctx context.Context) error {
select {
case <-time.After(2 * time.Second):
return fmt.Errorf("Operation completed")
case <-ctx.Done():
return ctx.Err()
}
}
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
defer cancel()
if err := operation(ctx); err != nil {
fmt.Println("Error:", err)
}
// Context with value
ctx2 := context.WithValue(context.Background(), "userID", 42)
fmt.Println(ctx2.Value("userID"))
}Explanation
context passes cancellation signals, timeouts, and values between goroutines.