// Homework 47, problem 3: Stop cleanly. // // This server uses http.HandleFunc and http.ListenAndServe, and prints with // fmt.Println. Change it so that: // - it uses its own ServeMux and an http.Server with the four time limits // - it logs with a slog text logger instead of fmt.Println // - Ctrl+C lets a running /wait request finish, logs "shutting down" and // "server stopped", and the program exits with code 0 // - the work is done in run(logger) error, and main exits with code 1 if // run returns an error, such as the port being in use // // Run with: go run exercises/47/homework/03-clean-stop.go // Then run curl.exe http://localhost:8080/wait and press Ctrl+C while it waits. package main import ( "fmt" "net/http" "time" ) func handleHome(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "Hello. Try /wait.") } // handleWait pretends to do 3 seconds of work. func handleWait(w http.ResponseWriter, r *http.Request) { time.Sleep(3 * time.Second) fmt.Fprintln(w, "Finished waiting.") } func main() { http.HandleFunc("GET /{$}", handleHome) http.HandleFunc("GET /wait", handleWait) fmt.Println("Server running at http://localhost:8080") fmt.Println("Press Ctrl+C to stop it.") // TODO: replace this with an http.Server and a clean shutdown. err := http.ListenAndServe("localhost:8080", nil) if err != nil { fmt.Println("Server stopped:", err) } }