×

go · level 2 · unit 7 · lesson 2

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

A picks the , and a says how it went.

A server answers many paths, and each route needs its own answer. A switch compares one value with several case lines and runs the first that matches, while default catches everything else. It is a tidier way to write a long else if chain.

Every reply has a status code: 200 means OK, 400 bad request, 404 not found and 405 wrong method. http.Error(w, "no such page", http.StatusNotFound) sends a status code and a short message in one go.

A web address can carry extra values after a ?, called the : /hello?name=Sam. r.URL.Query().Get("name") reads one. It gives "" when the value is missing, so check before you rely on it.

package main
import "fmt"
import "net/http"
import "net/http/httptest"
func site(w http.ResponseWriter, r *http.Request) {
	switch r.URL.Path {
	case "/hello", "/hi":
		fmt.Fprintf(w, "Hello, %s!", r.URL.Query().Get("name"))
	default:
		http.Error(w, "no such page", http.StatusNotFound)
	}
}
func main() {
	for _, target := range []string{"/hello?name=Sam", "/hi?name=Ava", "/secret"} {
		rec := httptest.NewRecorder()
		site(rec, httptest.NewRequest("GET", target, nil))
		fmt.Println(rec.Code, rec.Body.String())
	}
}

A case can list several values with commas, and Go never runs on into the next case.