Gracefully shutdown the HTTP server
In Chapter 1, Interacting with the Environment, the mechanism of how to implement graceful shutdown was presented. In this recipe, we will describe how to shut down the HTTP server and give it time to handle the existing clients.
How to do it...
- Open the console and create the folder
chapter09/recipe11
. - Navigate to the directory.
- Create the file
gracefully.go
with the following content:
package main import ( "context" "fmt" "log" "net/http" "os" "os/signal" "time" ) func main() { mux := http.NewServeMux() mux.HandleFunc("/",func(w http.ResponseWriter, r *http.Request){ fmt.Fprintln(w, "Hello world!") }) srv := &http.Server{Addr: ":8080", Handler: mux} go func() { if err := srv.ListenAndServe(); err != nil { log.Printf("Server error: %s\n", err) } ...