Graceful Shutdown Context Signal
Stop an HTTP server gracefully on SIGTERM, draining connections with a bounded context deadline before forcing closure.
Code
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")
}Report a problem with this exampleOpens a pre-filled issue on GitHub.