liveBook · Manning

Routing

As explained in Learn Go with Pocket-Sized Projects

A multiplexer is a web-serving component or library that matches incoming requests to handlers and manages their routing.

A server with several endpoints needs more than one handler passed directly to `http.ListenAndServe`. A request multiplexer, or mux, selects a handler from the request’s URL. Go’s `http.ServeMux` implements `http.Handler`, so the same mux can hold the routes and serve as the argument to `ListenAndServe`. section 8.2.1

Create a mux with `http.NewServeMux()`, register a pattern and handler with `HandleFunc`, then pass the mux to `http.ListenAndServe`. Keeping registration in a `NewRouter` or `Router` function gives the service one place to assemble its endpoints. A handler registered this way is a function with the signature `func(http.ResponseWriter, *http.Request)`. section 8.2.1 section 11.1.1

Listing 8.10 internal/handlers/router.go: Setting the verb and path
package handlers

import (
    "net/http" 

    "learngo-pockets/httpgordle/internal/api"
    "learngo-pockets/httpgordle/internal/handlers/newgame"
)

// NewRouter returns a router that listens for requests
// to the following endpoints:
//   - Create a new game;
//
// The provided router is ready to serve.
func NewRouter() *http.ServeMux { 
    r := http.NewServeMux()
    r.HandleFunc(http.MethodPost+" "+api.NewGameRoute, #1
        newgame.Handle)  #1


    return r
}

The `POST /games` pattern associates both a method and a path with the new-game handler. The returned mux is ready to serve. section 8.2.1

Check the route from a terminal

Start the server on port 8080 and try `curl -v localhost:8080/games`: a GET receives `405 Method Not Allowed`. Try `curl -v -X POST localhost:8080/games` to reach the new-game handler. An early version returns `200 OK` and a placeholder message; the handler is then changed to return `201 Created`. This makes the route’s method and the response behavior visible separately. section 8.2.1

Routing selects the handler; the handler still owns the response. It can set headers, write a status, and write a body. If it needs a status other than the default `200 OK`, it must call `WriteHeader` before writing the body. Route registration can therefore keep method selection out of a handler, while response construction stays inside it. section 8.2.1 section 8.7

The same arrangement works for a page: a server’s `Router` method creates a mux, registers `GET /` to its index method, and returns the mux as an `http.Handler`. Handler behavior can be checked with `httptest.NewRecorder`; a new-game test checks the status, content type, and JSON body. The standard-library mux is the choice shown here, though open-source routing libraries are another option. section 11.1.1 section 8.2.1

How Learn Go with Pocket-Sized Projects covers it

How deep it goes
Works through mux construction, method-and-path registration, server wiring, and request checks; leaves response construction to handlers.
Examples
Uses `POST /games`, GET and POST curl requests, and a `GET /` page route.
What it assumes
Assumes familiarity with Go functions and HTTP requests while showing how `ServeMux` fulfills the `http.Handler` interface.
What you can do after
Build it from scratch with `http.NewServeMux`, register method-and-path handlers, and pass the router to `http.ListenAndServe`.
How it connects
Connects `http.ServeMux` with `http.Handler`, `HandleFunc`, `http.ListenAndServe`, and `http.ResponseWriter`.

Also explained in

Compare how 22 books explain routing →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Go with Pocket-Sized Projects. The section links point to the parts of the book it draws on.