TIL about signal.NotifyContext, allowing one to handle graceful shutdown on a signal as a regular context cancellation, without having to setup a buffered channel or separate goroutine. Graceful shutdown simply becomes the following:
package main
import (
"context"
"os"
"os/signal"
"syscall"
)
func main() {
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
doThing(ctx) // assuming thing handles context cancellation gracefully
shutdown()
}
Very useful. I’m probably more likely to remember to add graceful shutdowns in my tools now.