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
context.WithCancel creates a switch that can turn off a running task from anywhere in your code. It is like a remote control for a background process, allowing you to stop it cleanly without waiting for it to finish naturally. You use it to prevent your program from wasting resources on tasks that are no longer needed.