How to use context package

Use the context package to manage deadlines, cancellation, and request-scoped values across goroutines and API boundaries.

Use the context package 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("Task completed")
	case <-ctx.Done():
		fmt.Println("Context cancelled or timed out:", ctx.Err())
	}
}