How to Implement the Context-Based Cancellation Pattern

Implement context-based cancellation in Go by deriving child contexts and checking ctx.Done() to stop tasks immediately.

Implement context-based cancellation by creating a parent context, deriving child contexts for tasks, and checking ctx.Err() or using select to stop execution when the parent is canceled.

ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()

// Start a goroutine that respects cancellation
func worker(ctx context.Context) {
    select {
    case <-ctx.Done():
        fmt.Println("Task canceled:", ctx.Err())
        return
    case <-time.After(2 * time.Second):
        fmt.Println("Task completed")
    }
}

worker(ctx)