// Chapter 33 example: reading values from the path. // Run with: go run exercises/33/02-path-values.go package main import ( "fmt" "net/http" "strconv" ) func handlePlayer(w http.ResponseWriter, r *http.Request) { name := r.PathValue("name") w.Header().Set("Content-Type", "text/plain; charset=utf-8") fmt.Fprintf(w, "This is the page of %s.\n", name) } func handleSquare(w http.ResponseWriter, r *http.Request) { n, err := strconv.Atoi(r.PathValue("n")) if err != nil { http.Error(w, "The path must end in a whole number.", http.StatusBadRequest) return } if n < -1000 || n > 1000 { http.Error(w, "The number must be from -1000 to 1000.", http.StatusBadRequest) return } fmt.Fprintf(w, "%d squared is %d\n", n, n*n) } func main() { http.HandleFunc("GET /players/{name}", handlePlayer) http.HandleFunc("GET /square/{n}", handleSquare) 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) } }