How to use context for goroutine cancellation

Use context.WithCancel to create a cancellable context and check ctx.Done() inside goroutines to stop execution gracefully.

Pass a context.Context to your goroutine and check ctx.Err() or use ctx.Done() to stop execution when the parent context is canceled.

ctx, cancel := context.WithCancel(context.Background())

// Start the goroutine with the context
go func(ctx context.Context) {
    select {
    case <-ctx.Done():
        // Context canceled, exit immediately
        return
    case <-time.After(5 * time.Second):
        // Do work
    }
}(ctx)

// Cancel later to stop the goroutine
cancel()