valfz

The standard library router is enough

What Go's net/http ServeMux does since 1.22, shown on a small service with real requests on Go 1.27.3, and the limits that justify a third-party router.

topic
go and htmx
date
read
16 min

Since Go 1.22, http.ServeMux matches on HTTP method and on path wildcards, the two things it most visibly lacked next to third-party routers. This article builds a small service with HTML pages and a JSON API on the standard mux alone, shows what the mux answers at each step with real requests, and then states where it stops, so you can tell when a router dependency pays for itself.

Everything here was run on Go 1.27.3. The pattern syntax arrived in Go 1.22. Two later changes appear below: Request.Pattern was added in 1.23, and since Go 1.26 the redirects that the mux issues on its own use status 307 where they used 301.

One function holds the route table

The service is a bookshelf: an HTML page per book, a JSON API over the same data, and a directory of static files.

main.go
func routes(a *app) http.Handler {
	mux := http.NewServeMux()

	mux.HandleFunc("GET /{$}", a.home)
	mux.HandleFunc("GET /books/{id}", a.bookPage)
	mux.HandleFunc("GET /static/{path...}", a.static)

	mux.HandleFunc("GET /api/books", a.listBooks)
	mux.HandleFunc("POST /api/books", a.createBook)
	mux.HandleFunc("GET /api/books/{id}", a.getBook)
	mux.HandleFunc("GET /api/books/latest", a.latestBook)
	mux.HandleFunc("DELETE /api/books/{id}", a.deleteBook)

	return mux
}

func main() {
	a := &app{store: newStore()}
	log.Fatal(http.ListenAndServe("localhost:8894", routes(a)))
}

A pattern has the form [METHOD ][HOST]/[PATH]. Without a method it matches every method. GET also matches HEAD, and any other method matches only itself. {id} is a wildcard for exactly one path segment, and a handler reads the matched text with r.PathValue:

handlers.go
// bookFromPath resolves the {id} wildcard to a book, or writes the error
// response and reports false.
func (a *app) bookFromPath(w http.ResponseWriter, r *http.Request) (Book, bool) {
	id, err := strconv.Atoi(r.PathValue("id"))
	if err != nil {
		http.Error(w, "book id must be a number", http.StatusBadRequest)
		return Book{}, false
	}
	b, ok := a.store.get(id)
	if !ok {
		http.NotFound(w, r)
		return Book{}, false
	}
	return b, true
}

func (a *app) getBook(w http.ResponseWriter, r *http.Request) {
	if b, ok := a.bookFromPath(w, r); ok {
		writeJSON(w, http.StatusOK, b)
	}
}

The value is a string, already percent-decoded, and never empty: /api/books/ does not match {id}. What the string means is the handler’s business. The mux cannot require digits, so /api/books/abc reaches getBook, and getBook rejects it:

curl -i localhost:8894/api/books/abc
HTTP/1.1 400 Bad Request
Content-Type: text/plain; charset=utf-8
X-Content-Type-Options: nosniff
Date: Sat, 28 Nov 2026 21:52:28 GMT
Content-Length: 25

book id must be a number

Exact matches and the rest of the path

A pattern that ends in a slash matches every path underneath it. That makes GET / a catch-all for GET requests, which is rarely what a home page route should be. The special wildcard {$} matches only the end of the path, so GET /{$} serves / and nothing else, and an unknown path falls through to the mux’s own 404:

curl -i localhost:8894/nope
HTTP/1.1 404 Not Found
Content-Type: text/plain; charset=utf-8
X-Content-Type-Options: nosniff
Date: Sat, 28 Nov 2026 21:52:28 GMT
Content-Length: 19

404 page not found

{path...} is the named form of the trailing slash. It has to be the last element of the pattern, and it captures the remainder of the path, slashes included:

handlers.go
func (a *app) static(w http.ResponseWriter, r *http.Request) {
	name := r.PathValue("path") // "css/app.css" for /static/css/app.css
	if name == "" || strings.HasSuffix(name, "/") {
		http.NotFound(w, r) // no directory listings
		return
	}
	http.ServeFileFS(w, r, staticFS, name)
}

The remainder may be empty: /static/ matches with path set to "", which is why the handler checks for it. /static without the slash matches nothing, but the mux sees that adding a slash would produce a match and redirects:

curl -i localhost:8894/static
HTTP/1.1 307 Temporary Redirect
Content-Type: text/html; charset=utf-8
Location: /static/
Date: Sat, 28 Nov 2026 21:52:28 GMT
Content-Length: 44

<a href="/static/">Temporary Redirect</a>.

Before Go 1.26 this redirect was a 301, which a client may cache, and may follow with a GET even when the original request was a POST (RFC 9110). A 307 keeps the method. The mux sends the same 307 for a path with .. segments or doubled slashes, such as //api//books, pointing at the cleaned path.

What a wrong method gets

The table has GET and DELETE routes for a single book, and nothing for PUT:

curl -i -X PUT localhost:8894/api/books/1
HTTP/1.1 405 Method Not Allowed
Allow: DELETE, GET, HEAD
Content-Type: text/plain; charset=utf-8
X-Content-Type-Options: nosniff
Date: Sat, 28 Nov 2026 21:52:28 GMT
Content-Length: 19

Method Not Allowed

No handler in the service wrote that response. When nothing matches a request, the mux looks for patterns that match the same host and path under other methods. If there are any, it answers 405 and lists their methods in Allow. If there are none, it answers 404. HEAD is in the list because every GET pattern serves it.

Two things follow from this. OPTIONS is one more method without a pattern, so a CORS preflight gets a 405 until you register OPTIONS patterns or put a CORS middleware in front of the mux. And a catch-all without a method, such as mux.Handle("/", notFound), matches every method on every path, so the mux never reaches the 405 branch: PUT /api/books/1 gets whatever the catch-all returns.

Precedence and conflicts

Both GET /api/books/{id} and GET /api/books/latest match a request for /api/books/latest. The mux picks the most specific pattern, and the definition is set-based: one pattern is more specific than another when it matches a strict subset of the other’s requests. Registration order plays no part. In the table above, latest is registered after {id} and still wins:

curl localhost:8894/api/books/latest
{"id":2,"title":"The C Programming Language","author":"Kernighan and Ritchie"}

If two patterns overlap and neither is a subset of the other, there is no winner, and the mux panics when the second one is registered. Take this pair, which both match /books/latest:

main.go
mux := http.NewServeMux()
mux.HandleFunc("GET /books/{id}", h)
mux.HandleFunc("GET /{section}/latest", h)

Running the program with go run -trimpath . (the flag shortens the file paths in the message) ends like this, before a single request is served:

panic: pattern "GET /{section}/latest" (registered at example.com/conflict/main.go:10) conflicts with pattern "GET /books/{id}" (registered at example.com/conflict/main.go:9):
	GET /{section}/latest and GET /books/{id} both match some paths, like "/books/latest".
	But neither is more specific than the other.
	GET /{section}/latest matches "/section/latest", but GET /books/{id} doesn't.
	GET /books/{id} matches "/books/id", but GET /{section}/latest doesn't.
...

The message names both registration sites and gives a path that both patterns match. Because the panic happens inside HandleFunc, a test that does nothing but call routes catches every conflict before deployment.

Here is what registering some other pairs does on Go 1.27.3:

Patterns Result
GET /books/{id} and GET /books/latest Accepted. The literal segment is more specific.
/books/{id} and GET /books/{id} Accepted. GET and HEAD go to the pattern with a method.
GET /books/{id} and GET /books/{name} Panic: one “matches the same requests as” the other.
GET /static/ and GET /static/{path...} Panic, for the same reason.
GET / and /index.html Panic: /index.html “matches more methods than GET /, but has a more specific path pattern”.

Pattern strings are parsed at registration too, and a malformed one panics with a position, for example parsing "GET books": at offset 4: host/path missing /. Two mistakes get past the parser. get /books is a valid pattern for a method named get, which real clients do not send. GET/books, with the space missing, is a valid pattern for the path /books on a host named GET. Both register without complaint and never match.

Host patterns

A pattern may name a host before the path. One line gives the bookshelf an admin page on its own hostname:

main.go
mux.HandleFunc("GET admin.localhost/{$}", a.adminHome)
curl -H 'Host: admin.localhost:8894' localhost:8894/
admin: 2 books on the shelf

The port is ignored when matching, and every other host still gets the home page from GET /{$}. Hosts are literal. GET {tenant}.example.com/ is rejected at registration (host contains '{'), so per-tenant subdomains mean reading r.Host in a handler or a middleware.

Host patterns also carry the one exception to the precedence rule. example.com/ and GET / overlap and neither is a subset of the other, which would normally be a conflict. For compatibility with programs written before Go 1.22, the mux accepts the pair and lets the pattern with a host win.

Middleware is a function that wraps a handler

The mux has no middleware API. A middleware is a func(http.Handler) http.Handler, the mux is an http.Handler, and so is each route’s handler. What you wrap decides how far a middleware reaches.

middleware.go
type middleware func(http.Handler) http.Handler

// logRequests logs after the handler has run, when the mux has filled
// in r.Pattern.
func logRequests(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		next.ServeHTTP(w, r)
		log.Printf("%s %s -> %q", r.Method, r.URL.Path, r.Pattern)
	})
}

func noStore(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Cache-Control", "no-store")
		next.ServeHTTP(w, r)
	})
}

func requireToken(token string) middleware {
	want := []byte("Bearer " + token)
	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			got := []byte(r.Header.Get("Authorization"))
			if subtle.ConstantTimeCompare(got, want) != 1 {
				w.Header().Set("WWW-Authenticate", "Bearer")
				http.Error(w, "unauthorized", http.StatusUnauthorized)
				return
			}
			next.ServeHTTP(w, r)
		})
	}
}

logRequests is meant to wrap the whole mux, which puts it in front of routing. It can still log the route, because ServeMux writes the matched pattern into r.Pattern on the request it was handed, and the middleware reads the field after next.ServeHTTP returns. The pattern is a better label for logs and metrics than the raw path, since /books/1 and /books/2 share one.

Grouping routes under a prefix

Wrapping one route is a function call around its handler. Wrapping a group takes a second mux: register the group’s routes on it without the prefix, wrap it, and mount it on the main mux with http.StripPrefix.

main.go
func routes(a *app, token string) http.Handler {
	mux := http.NewServeMux()

	mux.HandleFunc("GET /{$}", a.home)
	mux.HandleFunc("GET /books/{id}", a.bookPage)
	mux.HandleFunc("GET /static/{path...}", a.static)
	mux.HandleFunc("GET admin.localhost/{$}", a.adminHome)

	auth := requireToken(token)

	api := http.NewServeMux()
	api.HandleFunc("GET /books", a.listBooks)
	api.Handle("POST /books", auth(http.HandlerFunc(a.createBook)))
	api.HandleFunc("GET /books/{id}", a.getBook)
	api.HandleFunc("GET /books/latest", a.latestBook)
	api.Handle("DELETE /books/{id}", auth(http.HandlerFunc(a.deleteBook)))

	mux.Handle("/api/", http.StripPrefix("/api", noStore(api)))

	return logRequests(mux)
}

logRequests covers every request. noStore covers the API and adds Cache-Control: no-store to its responses. auth covers the two routes that change data. With the server started as BOOKSHELF_TOKEN=s3cret go run .:

curl -i -X DELETE localhost:8894/api/books/2
HTTP/1.1 401 Unauthorized
Cache-Control: no-store
Content-Type: text/plain; charset=utf-8
Www-Authenticate: Bearer
X-Content-Type-Options: nosniff
Date: Sat, 28 Nov 2026 21:52:28 GMT
Content-Length: 13

unauthorized
curl -i -X DELETE -H 'Authorization: Bearer s3cret' localhost:8894/api/books/2
HTTP/1.1 204 No Content
Cache-Control: no-store
Date: Sat, 28 Nov 2026 21:52:28 GMT

The inner mux does its own matching, so wrong methods under /api/ still get a 405 with the right Allow header. The arrangement has two costs, and both come from the inner mux seeing a different path than the one the client sent.

First, StripPrefix passes a copy of the request to the inner mux, so the pattern that the inner mux matched never reaches the outer middleware. This is the server log after the admin request from the host section, one book page view, and the two DELETE requests:

GET / -> "GET admin.localhost/{$}"
GET /books/1 -> "GET /books/{id}"
DELETE /api/books/2 -> "/api/"
DELETE /api/books/2 -> "/api/"

Second, the inner mux builds its redirects from the stripped path. Give it a subtree pattern such as GET /docs/, and a request for /api/docs is redirected to /docs/, which does not exist.

Both problems go away when the inner mux registers full paths (GET /api/books/{id}) and is mounted without StripPrefix, as mux.Handle("/api/", noStore(api)). The outer middleware then logs "GET /api/books/{id}" and the redirect points at /api/docs/. The price is the prefix repeated in every pattern.

Where it stops

Wildcards take no constraints. GET /books/{id:[0-9]+} panics at registration with bad wildcard name "id:[0-9]+". A wildcard also has to be a whole segment, so /books/{id}.json is rejected. Validation moves into the handler, as in bookFromPath. The larger consequence is that the mux cannot route on the shape of a segment: /books/{id} and /books/{slug} are one pattern as far as it is concerned.

There are no route groups. The sub-mux is the idiom, with the costs described above. One level of nesting is manageable. A tree of groups, each adding middleware to what its parent set up, becomes bookkeeping that a router would do for you.

There are no named routes and no URL generation. createBook builds its Location header by concatenating "/api/books/" with the new id, and nothing ties that string to the pattern. Rename the route and the compiler stays silent.

The 404 and 405 responses have no hook. They are plain text written by the mux, even inside a JSON API, and the catch-all that would replace the 404 also swallows the 405. What does work is a middleware that wraps the ResponseWriter and rewrites any 404 or 405 written while r.Pattern is still empty, which is the case only for the mux’s own responses. That is about thirty lines you have to own.

When one of these limits is the thing you keep working around, a third-party router is the better choice, and the switch costs little as long as the router speaks net/http. chi does: its handlers and middleware are the standard types, and it adds nested groups (Route, Group, With), regular expressions on parameters ({articleSlug:[a-z-]+}) and NotFound and MethodNotAllowed hooks. gorilla/mux adds named routes with URL building (r.Get("article").URL("category", "technology", "id", "42")), though its latest tagged release, v1.8.1, dates from October 2023.

A service whose routes fit in one function, like the bookshelf, has not hit those limits. The standard mux already reports conflicts at startup and answers wrong methods correctly, and the only thing to keep up to date is Go itself.

keyboard

h
home
w c a
writing, courses, about
n p
next and previous lesson
j k
scroll down and up
g G
top and bottom of the page
t
switch light and dark
?
this help

shortcuts are