Using context for cancellations
There are several reasons why you might want to cancel a computation: the client may have disconnected, or you may have multiple goroutines working on a computation and one of them failed, so you no longer want the others to continue. You can use other methods, such as a done
channel that you close to signal cancellation, but a context can be more convenient depending on the use case. A context can be canceled many times (only the first call will actually cancel; the remaining ones will be ignored), whereas you cannot close an already closed channel as it will panic. Also, you can create a tree of contexts where canceling one context only cancels goroutines controlled by it, without affecting others.
How to do it...
These are the steps to create a cancelable context and to detect a cancellation:
- Use
context.WithCancel
to create a new cancelable context based on an existing context, and a cancellation function:ctx:=context.Background() cancelable...