×

go · level 2 · unit 7 · lesson 1

  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 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.