Handlers, ServeMux and patterns

http.ServeMux is the router of the standard library, and since Go 1.22 its patterns carry a method and a path variable: GET /notes/{id} matches a GET of one segment and puts the segment in r.PathValue("id"). A mux with method patterns also answers 405 by itself, which is the part a hand-written router usually forgets. The programs here call the mux with httptest and read the recorder, so no port is opened.

ServeMux and method patterns

Two patterns cover the collection and one item. A pattern with {id} matches exactly one path segment and binds it; the more specific pattern wins, so /notes/42 reaches the item handler and /notes the list. The recorder holds the status and the body the handler produced.

package main import ( "fmt" "net/http" "net/http/httptest" "strings" ) func main() { mux := http.NewServeMux() mux.HandleFunc("GET /notes/{id}", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "note %s\n", r.PathValue("id")) }) mux.HandleFunc("GET /notes", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "list of notes") }) for _, target := range []string{"/notes", "/notes/42"} { req := httptest.NewRequest("GET", target, nil) rec := httptest.NewRecorder() mux.ServeHTTP(rec, req) fmt.Printf("%s -> %d %q\n", target, rec.Code, strings.TrimSpace(rec.Body.String())) } }

go build -o app main.go && ./app

/notes -> 200 "list of notes"
/notes/42 -> 200 "note 42"

The path value is a string and the handler decides what it means; a mux does not check that 42 is a number. A pattern with a trailing ... such as GET /files/{path...} matches the rest of the path, and a pattern with {$} matches only the exact path, which is how / stops being a catch-all.

404 and 405

A path the mux does not know is a 404 with a short plain-text body. A path it knows with a method it does not is a 405, and the mux fills the Allow header with the methods that would have worked. Both answers come before a handler runs, so a program does not need its own guard for them.

package main import ( "fmt" "net/http" "net/http/httptest" ) func main() { mux := http.NewServeMux() mux.HandleFunc("GET /notes", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "list") }) for _, tc := range []struct{ method, path string }{ {"GET", "/missing"}, {"POST", "/notes"}, } { req := httptest.NewRequest(tc.method, tc.path, nil) rec := httptest.NewRecorder() mux.ServeHTTP(rec, req) fmt.Printf("%s %s -> %d allow=%q\n", tc.method, tc.path, rec.Code, rec.Header().Get("Allow")) } }

go build -o app main.go && ./app

GET /missing -> 404 allow=""
POST /notes -> 405 allow="GET, HEAD"

The 405 names both GET and HEAD because a GET pattern answers a HEAD too, and the 404 has no Allow header at all. A client can act on the difference: a 404 means the resource does not exist, a 405 means the method is wrong for a resource that does.

A handler for everything else

A pattern of / matches every path that nothing else matched, which is how a program adds its own 404 page or serves a single-page app. The handler below answers with a custom message and a 404, and the more specific /api/ pattern still wins for its subtree.

package main import ( "fmt" "net/http" "net/http/httptest" ) func main() { mux := http.NewServeMux() mux.HandleFunc("/api/", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "api") }) mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusNotFound) fmt.Fprintf(w, "no such page: %s\n", r.URL.Path) }) req := httptest.NewRequest("GET", "/blog/post", nil) rec := httptest.NewRecorder() mux.ServeHTTP(rec, req) fmt.Println("status:", rec.Code) fmt.Print("body: ", rec.Body.String()) }

go build -o app main.go && ./app

status: 404
body: no such page: /blog/post

The program wrote the status before the body, so the response is a 404 and not a 200. A single-page app returns index.html with a 200 from this handler instead, and lets its client-side router show the page; an API returns a JSON error, which is what the next lessons do.

The trailing slash redirect

A pattern that ends in a slash is a subtree, and the mux redirects a request for the name without the slash to the name with it. The status is 307 in this Go version, not 301: a 307 keeps the method and the body, so a POST is not turned into a GET by the redirect.

package main import ( "fmt" "net/http" "net/http/httptest" ) func main() { mux := http.NewServeMux() mux.HandleFunc("/notes/", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "subtree", r.URL.Path) }) req := httptest.NewRequest("GET", "/notes", nil) rec := httptest.NewRecorder() mux.ServeHTTP(rec, req) fmt.Println("status:", rec.Code) fmt.Println("location:", rec.Header().Get("Location")) }

go build -o app main.go && ./app

status: 307
location: /notes/

The browser follows the Location and the user sees the page, so the redirect is not an error in practice. A program that wants one address and no redirect registers the exact path and handles both forms itself, which is the choice an API makes when a client would rather not follow redirects.

Patterns that stay readable

The mux has no middleware, no regular expressions and no named routes, and that is enough for a service of a few dozen endpoints. Three habits keep it readable: one registration block per resource with the patterns next to each other, a comment above a pattern only when the path is unusual, and the version of the API in the path (/v1/notes) rather than in a header when there is one. A router library earns its place when the patterns need a regexp or when the middleware chain is deep; the next lesson shows that a chain is a function too.

The API capstone registers its routes in one file and keeps the handlers in another, and the tests call the mux with httptest exactly as these programs do. A test that needs a real socket uses httptest.NewServer, which is in the HTTP client lesson.

Exercises

  1. Add a pattern GET /notes/{id}/comments/{cid} and read both values. Which segment does each name bind, and what happens with a missing one?
  2. Change the fallback to return 200 and an HTML page. Which request now reaches it, and why is the status a decision rather than a detail?
  3. Register the same pattern twice and run the program. What does the mux do at registration, and why is that better than the last one winning?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does a pattern with {id} match?

    Answer

    Exactly one path segment, available as a path value

    A trailing ... matches the rest.

  2. What does the mux answer for a known path and a wrong method?

    Answer

    405 with an Allow header

    The Allow header lists the methods that work.

  3. What does a pattern of / match?

    Answer

    Every path that no other pattern matched

    It is the fallback.

  4. What does a pattern ending in a slash mean?

    Answer

    A subtree

    The mux redirects the bare name to it.

  5. Which status does the trailing slash redirect use in this version?

    Answer

    307

    A 307 keeps the method and the body.

  6. What does httptest.NewRecorder collect?

    Answer

    The status, the headers and the body of a handler

    It implements ResponseWriter.

  7. What does {$} at the end of a pattern do?

    Answer

    Matches only that exact path

    It stops / from being a catch-all.

  8. Why does the 404 above have no Allow header?

    Answer

    The path does not exist, so no method would work

    Allow describes a resource that exists.

  9. When does a router library earn its place?

    Answer

    When patterns need regexps or middleware is deep

    The standard mux covers a small service.

  10. What does {path...} match?

    Answer

    The rest of the path, slashes included

    It is the form a file server uses.

The code on this page was run with go 1.26.10 on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev