go · level 2 · unit 7 · lesson 1
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
A is the function that answers a web .
When you visit a web page, your browser sends a request using : a method such as GET and a path such as /hello. The server sends back a reply: a status code saying how it went, and a body, which is the page itself.
In Go, a handler answers one request: func hello(w http.ResponseWriter, r *http.Request). r holds the request, so r.Method is its method and r.URL.Path its path. w is where your reply goes, and it is an io.Writer, so fmt.Fprintf(w, "Hello!") writes the body.
On Gwecode there is no real network, so test handlers with . httptest.NewRequest("GET", "/hello", nil) makes a pretend request, and rec := httptest.NewRecorder() catches the reply. Call hello(rec, req), then read rec.Code and rec.Body.String().
package main
import "fmt"
import "net/http"
import "net/http/httptest"
func hello(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello from %s!", r.URL.Path)
}
func main() {
req := httptest.NewRequest("GET", "/hello", nil)
rec := httptest.NewRecorder()
hello(rec, req)
fmt.Println("Status:", rec.Code)
fmt.Println("Body:", rec.Body.String())
} The nil in NewRequest means the request carries no body, which is normal for GET.
guess first
A pretend POST request. What will this show?
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 whoami(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "You sent a", r.Method, "request")
}
func main() {
rec := httptest.NewRecorder()
whoami(rec, httptest.NewRequest("POST", "/me", nil))
fmt.Print(rec.Code, " ", rec.Body.String())
}
your turn
Your turn. Open a shop on the web.
Name your shop in the first blank. Choose a path for the pretend request, with no spaces. Then call the shop handler, handing it the recorder and the request.
output
press run to see what happens
fix it
The ping never gets its pong. Fix it!
output
press run to see what happens
- Read the error. Which argument on line 11 does Go say has the wrong type?
- A handler takes the reply writer first and the request second:
w, thenr. - Change ping(req, rec) to ping(rec, req) on line 11, then run.
nailed it
you wrote your first web handler. :D
- A handler answers a request by writing its reply to
w. httptestmakes pretend requests and records the replies.rec.Codeis the status, andrec.Body.String()is the reply.
new words in your collection
- HTTP
- request
- handler
- httptest
This lesson isn’t saved. A free account remembers every lesson you finish.