Documentation
¶
Overview ¶
Package shutdown provides a single-call graceful shutdown helper for net/http servers. It catches SIGTERM and SIGINT, stops accepting new connections, waits for in-flight requests to complete, then exits.
Every production Go HTTP service needs graceful shutdown. Without it a SIGTERM during a deploy kills in-flight requests mid-response, causing 5xx errors visible to clients. This package encapsulates the canonical net/http.Server.Shutdown pattern so each service doesn't re-implement it.
Usage (replaces log.Fatal(srv.ListenAndServe())):
srv := &http.Server{Addr: ":8080", Handler: myHandler}
log.Fatal(shutdown.ListenAndServe(srv))
With options:
log.Fatal(shutdown.ListenAndServe(srv,
shutdown.WithDrainTimeout(15*time.Second),
shutdown.WithNotify(func(sig os.Signal) {
log.Printf("shutdown signal: %v", sig)
}),
))
The function returns nil on clean shutdown, or the server error if it fails for any reason other than http.ErrServerClosed.
Deprecated: use server.New and Server.Start, which on SIGTERM or SIGINT stop accepting connections and drain in-flight requests (30 seconds by default, server.WithDrainTimeout); server.WithGracefulDrain adds a readiness phase first (/readyz answers 503 while the load balancer moves traffic away). A program that builds its own http.Server can use signal.NotifyContext and http.Server.Shutdown from the standard library. server has no counterpart for TLS (ListenAndServeTLS), extra signals (WithSignals) or a notify callback (WithNotify); if you need one of those, say so before this package is removed. Removal no earlier than v0.104.0.
Index ¶
Constants ¶
const DefaultDrainTimeout = 30 * time.Second
DefaultDrainTimeout is the time allowed for in-flight requests to complete before the server forcefully closes connections. The default is conservative (30s) because fleet services may have long-lived SSE or streaming connections. Override with WithDrainTimeout.
Variables ¶
This section is empty.
Functions ¶
func ListenAndServe ¶
ListenAndServe starts srv and blocks until a SIGTERM or SIGINT is received, then performs a graceful shutdown with the configured drain timeout. Returns nil on clean shutdown, or the ListenAndServe error on startup failure.
This is a drop-in replacement for log.Fatal(srv.ListenAndServe()).
Types ¶
type Option ¶
type Option func(*Options)
Option is a functional option for ListenAndServe.
func WithDrainTimeout ¶
WithDrainTimeout sets how long to wait for in-flight requests to finish before forcing closure. Recommended values: 5–30s.
func WithNotify ¶
WithNotify sets a callback invoked when a shutdown signal is received. Use it to log the signal, emit a metric, or begin pre-shutdown work (e.g. deregistering from a service registry).
func WithSignals ¶
WithSignals adds OS signals to listen for in addition to SIGTERM and SIGINT. Useful for SIGUSR1-triggered reload scenarios.