Bitpath

Boss lesson · Unit 04

An HTTP service

Handlers, routes, JSON and middleware, tested without a port.

13 exercisesabout 3 min

What you practise

  • Handlers, routing, JSON in and out, middleware as a function wrapping a handler, tested without opening a port

Try a question from this lesson

Pick one

An HTTP handler is a function with this signature. Here a test calls it directly with a made-up request and a recorder, and no server is running. What prints?

Go
hello := func(w http.ResponseWriter,
  r *http.Request) {
  name := r.URL.Query().Get("name")
  fmt.Fprint(w, "hi ", name)
}

req := httptest.NewRequest(
  "GET", "/?name=ana", nil)
rec := httptest.NewRecorder()
hello(rec, req)
fmt.Println(rec.Code, rec.Body.String())

The ideas

Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.

Concept

Handlers

A handler receives two things. r *http.Request is what the client sent: method, URL, headers, body. w http.ResponseWriter is where the answer goes. It is an io.Writer, so fmt.Fprint(w, ...) writes the body.

A response goes out in order: headers, then the status code with w.WriteHeader, then the body. httptest.NewRecorder is a ResponseWriter that records all three, so a test needs no network.

Go
hello := func(w http.ResponseWriter,
  r *http.Request) {
  w.Header().Set("X-Greeting", "yes")
  w.WriteHeader(http.StatusOK) // 200
  fmt.Fprint(w, "hello")
}

rec := httptest.NewRecorder()
hello(rec, nil)
fmt.Println(rec.Code, rec.Body.String())
// 200 hello

Concept

Routing with ServeMux

A ServeMux is a router: it matches each request against registered patterns and calls the handler of the best match. A pattern can name a method and can contain wildcards in braces: "GET /items/{id}". The handler reads the wildcard with r.PathValue("id").

A mux is itself a handler, with a ServeHTTP method. A real program passes it to http.ListenAndServe; a test calls mux.ServeHTTP with a recorder.

Go
mux := http.NewServeMux()
mux.HandleFunc("GET /items/{id}", getItem)
mux.HandleFunc("POST /items", addItem)

// inside getItem:
//   id := r.PathValue("id")

// a real program would now block here:
//   http.ListenAndServe(":8080", mux)

Concept

Middleware

Logging, authentication and timing apply to every route. Instead of repeating them in each handler, write a function that takes a handler and returns a new one. The new handler does its extra work and calls the original.

That is all middleware is: a function wrapping a handler. Wrappers stack, the outermost runs first, and each one can decide not to call the next at all. The version below works on http.HandlerFunc, the function form of a handler.

Go
logging := func(
  next http.HandlerFunc,
) http.HandlerFunc {
  return func(w http.ResponseWriter,
    r *http.Request) {
    fmt.Println(r.Method, r.URL.Path)
    next(w, r) // run the wrapped handler
  }
}

9 more exercises in the app

  • 2× fill the blanks
  • 4× type the answer
  • 2× multiple choice
  • 1× order the lines

Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.

One email when Bitpath is ready to try. Nothing else. Privacy