Signals
signal.NotifyContext ties a context to SIGINT/SIGTERM - cancel it to propagate graceful shutdown to every goroutine that respects context cancellation.
A signal is a short message from the operating system to a running program, often asking it to stop. signal.NotifyContext turns selected signals into a context stop signal.
When the context is cancelled, code that checks it can stop its work. Call the returned stop function when signal handling is no longer needed.
package main
import (
"context"
"fmt"
"os"
"os/signal"
"syscall"
)
func main() {
ctx, stop := signal.NotifyContext(
context.Background(), os.Interrupt, syscall.SIGTERM,
)
defer stop()
<-ctx.Done()
fmt.Println("shutdown requested")
}In production
SIGTERM is a common signal that asks a program to stop. Pass the signal context to workers and let a server finish requests already in progress before exiting. Cancellation does not force a goroutine to stop; its code must check the context and return.
Enjoyed this? Get more software craft delivered to your inbox.