💻 Tech
In Go, if you will run an anonymous Go routine within an API handler to perform a run-and-forget task, you should use a cancellable context to avoid leaking the Go routine. This is because the Go routine will continue to run even after the API handler has returned. Here’s an example:
go func() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
}()
The benefits for doing so are the following:
- Prevents resource leaks
- Allows you to cancel the Go routine if needed
- Allows you to propagate the cancellation signal to other Go routines; propagation means that if the parent context is cancelled, all child contexts are also cancelled