// Chapter 32 example: replying with a status code. // Run with: go run exercises/32/03-status-codes.go package main import ( "fmt" "net/http" ) func handleHome(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "Try /old, /private, /broken and /created.") } func handleOld(w http.ResponseWriter, r *http.Request) { http.NotFound(w, r) } func handlePrivate(w http.ResponseWriter, r *http.Request) { http.Error(w, "You may not see this page.", http.StatusForbidden) } func handleBroken(w http.ResponseWriter, r *http.Request) { http.Error(w, "Something went wrong on the server.", http.StatusInternalServerError) } func handleCreated(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusCreated) fmt.Fprintln(w, "This reply has the status 201 Created.") } func main() { http.HandleFunc("GET /{$}", handleHome) http.HandleFunc("GET /old", handleOld) http.HandleFunc("GET /private", handlePrivate) http.HandleFunc("GET /broken", handleBroken) http.HandleFunc("GET /created", handleCreated) fmt.Println("Server running at http://localhost:8080") fmt.Println("Press Ctrl+C to stop it.") err := http.ListenAndServe("localhost:8080", nil) if err != nil { fmt.Println("Server stopped:", err) } }