Graceful Shutdown Context Signal

Stop an HTTP server gracefully on SIGTERM, draining connections with a bounded context deadline before forcing closure.

GoResilience

Code

gosnippet
47 lines
package main

import (
	"context"
	"errors"
	"fmt"
	"log"
	"net/http"
	"os/signal"
	"syscall"
	"time"
)

func main() {
	mux := http.NewServeMux()
	mux.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintln(w, "ok")
	})

	srv := &http.Server{
		Addr:              ":8080",
		Handler:           mux,
		ReadHeaderTimeout: 5 * time.Second,
	}

	ctx, stop := signal.NotifyContext(
		context.Background(), syscall.SIGTERM, syscall.SIGINT,
	)
	defer stop()

	go func() {
		if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
			log.Fatalf("serve: %v", err)
		}
	}()

	<-ctx.Done() // 阻塞直到收到终止信号
	log.Println("shutdown signal received, draining")

	shutdownCtx, cancel := context.WithTimeout(context.Background(), 25*time.Second)
	defer cancel()

	if err := srv.Shutdown(shutdownCtx); err != nil {
		log.Printf("forced close after deadline: %v", err)
	}
	log.Println("server stopped cleanly")
}

How the snippet works

Graceful Shutdown Context Signal is built around the function main.

Nothing falls through silently — 2 checkpoints test err != nil on the way through. The task is handed to a goroutine and runs concurrently. The cleanup call is deferred to function exit — success, early return, and panic all covered.

Key statements

if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
	log.Fatalf("serve: %v", err)
}
shutdownCtx, cancel := context.WithTimeout(context.Background(), 25*time.Second)
<-ctx.Done() // 阻塞直到收到终止信号

Interactive Tools for This Topic

FAQ

How do you run Graceful Shutdown Context Signal?
Just run the file; everything it needs ships with the runtime itself.