How to Use context.WithCancel in Go

Create a cancellable context with context.WithCancel and call the returned cancel function to stop operations.

Use context.WithCancel to create a cancellable context and a cancel function that stops all operations using that context. Call the cancel function when you need to terminate the operation immediately.

ctx, cancel := context.WithCancel(context.Background())
defer cancel()
// Use ctx in your operations
// cancel() when done or on error