// Chapter 47 example: Ctrl+C lets requests that are running finish first. // Run with: go run exercises/47/05-graceful-shutdown.go // Then run curl.exe http://localhost:8080/slow in a second terminal, and press // Ctrl+C in the first one while it waits. package main import ( "context" "errors" "fmt" "log/slog" "net/http" "os" "os/signal" "time" ) func handleHome(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "Hello. Try /slow.") } // handleSlow pretends to do 5 seconds of work. func handleSlow(w http.ResponseWriter, r *http.Request) { time.Sleep(5 * time.Second) fmt.Fprintln(w, "Done, after 5 seconds.") } // run starts the server and waits for Ctrl+C. It returns an error only if the // server could not run or could not stop cleanly. func run(logger *slog.Logger) error { mux := http.NewServeMux() mux.HandleFunc("GET /{$}", handleHome) mux.HandleFunc("GET /slow", handleSlow) srv := &http.Server{ Addr: "localhost:8080", Handler: mux, ReadHeaderTimeout: 5 * time.Second, ReadTimeout: 10 * time.Second, WriteTimeout: 10 * time.Second, IdleTimeout: 60 * time.Second, } ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt) defer stop() // ListenAndServe runs in its own goroutine, so that this one can wait. serverErr := make(chan error, 1) go func() { serverErr <- srv.ListenAndServe() }() logger.Info("server starting", "addr", srv.Addr) select { case err := <-serverErr: return err case <-ctx.Done(): } // A second Ctrl+C now ends the program at once. stop() logger.Info("shutting down", "wait", "up to 10s") shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() err := srv.Shutdown(shutdownCtx) if err != nil { return fmt.Errorf("shutdown: %w", err) } // After Shutdown, ListenAndServe returns http.ErrServerClosed. That is the // normal way for it to end. err = <-serverErr if !errors.Is(err, http.ErrServerClosed) { return err } logger.Info("server stopped") return nil } func main() { logger := slog.New(slog.NewTextHandler(os.Stderr, nil)) err := run(logger) if err != nil { logger.Error("server failed", "err", err) os.Exit(1) } }