// Chapter 33 example: reading values from the query string. // Run with: go run exercises/33/01-query-string.go package main import ( "fmt" "net/http" "strconv" ) func handleHello(w http.ResponseWriter, r *http.Request) { name := r.URL.Query().Get("name") if name == "" { http.Error(w, "Please give a name, as in /hello?name=Keiko", http.StatusBadRequest) return } w.Header().Set("Content-Type", "text/plain; charset=utf-8") fmt.Fprintf(w, "Hello, %s!\n", name) } func handleAdd(w http.ResponseWriter, r *http.Request) { query := r.URL.Query() a, err := strconv.Atoi(query.Get("a")) if err != nil { http.Error(w, "a must be a whole number.", http.StatusBadRequest) return } b, err := strconv.Atoi(query.Get("b")) if err != nil { http.Error(w, "b must be a whole number.", http.StatusBadRequest) return } fmt.Fprintf(w, "%d + %d = %d\n", a, b, a+b) } func main() { http.HandleFunc("GET /hello", handleHello) http.HandleFunc("GET /add", handleAdd) 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) } }