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:

  1. shutdownCtx is deliberately context.Background, not ctx. If you pass the signal-derived context, it is already cancelled by the time Shutdown starts and the function returns immediately without actually waiting.
  2. ReadHeaderTimeout on the server is a defense against slowloris and one of the few HTTP server knobs I set on every service.
  3. 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 when Shutdown wedges.

See also /posts/the-panic-in-a-goroutine-that-took-down-prod/.