A graceful shutdown stops a web server without abruptly abandoning active work. The server listens for operating-system signals, stops accepting new connections, and gives current request handlers time to finish before exiting. section 2.3.2
A practical implementation follows this sequence:
- Create a signal channel and register interrupt and kill signals with signal.Notify. section 2.3.2
- Run ListenAndServe in a goroutine so the main flow can monitor the signal channel concurrently. section 2.3.2
- After a signal arrives, call the server's Shutdown method; it stops new connections and waits for current requests to complete. section 2.3.2
Listing 2.14 More graceful shutdown using signals
package main
import (
"fmt"
"net/http"
"os"
"os/signal"
"time"
)
func main() {
handleFunc := newHandler() #1
server := &http.Server{ #1
Addr: “:8080",
Handler: handleFunc,
}
ch := make(chan os.Signal, 1) #2
signal.Notify(ch, os.Interrupt, os.Kill) #2
go func() {
server.ListenAndServe() #3
}()
time.Sleep(5 * time.Second) #4
<-ch
if err := server.Shutdown(nil); err != nil {
panic(err)
}
}
type handler struct{}
func newHandler() *handler {
return &handler{}
}
func (h *handler) ServeHTTP(res http.ResponseWriter,
req *http.Request) { #5
query := req.URL.Query()
name := query.Get("name")
if name == "" {
name = "Inigo Montoya"
}
fmt.Fprint(res, "Hello, my name is ", name)
}
A complete Go server wires an HTTP handler, a signal channel, concurrent ListenAndServe execution, a wait, and Shutdown into one runnable example. section 2.3.2



