The context package in Go provides a way to carry deadlines, cancellation signals, and request-scoped values across API boundaries and between goroutines.
package main
import (
"context"
"fmt"
"time"
)
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
select {
case <-time.After(1 * time.Second):
fmt.Println("Operation completed")
case <-ctx.Done():
fmt.Println("Context cancelled or timed out:", ctx.Err())
}
}