go · level 2 · unit 7 · lesson 2
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
Someone POSTs to the menu. What status comes back?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
package main
import "fmt"
import "net/http"
import "net/http/httptest"
func menu(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case "GET":
fmt.Fprint(w, "tea, cake, toast")
default:
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
}
}
func main() {
rec := httptest.NewRecorder()
menu(rec, httptest.NewRequest("POST", "/menu", nil))
fmt.Println(rec.Code)
}
your turn
Your turn. Add an animal to the zoo server.
Add a route for an animal of your own: choose its path, with no spaces, and the sound it makes. Then send the pretend request to your new path.
output
press run to see what happens
fix it
The missing page says everything is fine. Fix it!
output
press run to see what happens
- The message says not found, but the status code says 200, which means OK. What sets the status?
fmt.Fprintonly writes the body.http.Errorsends a status code and a message together.- Change line 7 to http.Error(w, "page not found", http.StatusNotFound), then run.
nailed it
your server knows every route. :D
- A
switchruns the firstcasethat matches, ordefault. - Status codes say how it went: 200 OK, 404 not found.
r.URL.Query().Getreads a value from the query string.
new words in your collection
- route
- switch
- status code
- query string
This lesson isn’t saved. A free account remembers every lesson you finish.