Graceful shutdown with signal.NotifyContext
Go 1.16 introduced signal.NotifyContext, which returns a context that cancels on the given signals. Paired with http.Server.Shutdown, it is the whole graceful-shutdown pattern in maybe fifteen lines.
func main() {
ctx, stop := signal.NotifyContext(context.Background(),
os.Interrupt, syscall.SIGTERM)
defer stop()
srv := &http.Server{
Addr: ":8080",
Handler: router(),
ReadHeaderTimeout: 5 * time.Second,
}
go func() {
if err := srv.ListenAndServe(); err != nil &&
!errors.Is(err, http.ErrServerClosed) {
log.Fatalf("listen: %v", err)
}
}()
log.Printf("listening on %s", srv.Addr)
<-ctx.Done()
log.Printf("shutting down...")
shutdownCtx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
if err := srv.Shutdown(shutdownCtx); err != nil {
log.Printf("shutdown: %v", err)
}
}
A few points:
shutdownCtxis deliberatelycontext.Background, notctx. If you pass the signal-derived context, it is already cancelled by the timeShutdownstarts and the function returns immediately without actually waiting.ReadHeaderTimeouton the server is a defense against slowloris and one of the few HTTP server knobs I set on every service.defer stop()is important: it releases the signal handler so a second ctrl-C goes to the default handler and actually kills the process, useful whenShutdownwedges.
See also /posts/the-panic-in-a-goroutine-that-took-down-prod/.