skip to content
Alvin Lucillo

Cancellable context in Go

/ 1 min read

💻 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:

  1. Prevents resource leaks
  2. Allows you to cancel the Go routine if needed
  3. 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