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





















