ServeMux
http.ServeMux maps request patterns to handlers. Since Go 1.22 it understands methods, wildcards ({id}), and trailing-slash redirects. It is the default router.
Detailed Explanation
mux := http.NewServeMux() then mux.HandleFunc("GET /users/{id}", getUser) registers a route. Incoming requests are matched against the patterns. The most specific match wins. r.PathValue("id") reads the wildcard.
Patterns. "GET /health" matches GET (and HEAD, for GET registrations) on /health. "/static/" is a prefix-style tree in the new mux when written as a trailing-slash subtree — check the current docs for {$} (end) and {path...} (wildcard remainder). A pattern without a method matches every method.
The default mux. http.Handle registers on http.DefaultServeMux. Using the default in a library is a footgun: import side effects collide. Libraries should return a handler. main owns the mux.
Older Go. Before 1.22, ServeMux was prefix-based (/images/ vs /images) and had no method match. If you must support older toolchains, use a third-party router or r.Method checks inside the handler. The go line in go.mod is how you opt into 1.22 patterns.
What it costs. ServeMux is fast enough for typical APIs. A custom radix tree is rarely the bottleneck. The cost is learning the new pattern syntax once, and not mixing DefaultServeMux with tests that import _ "net/http/pprof" (which registers on the default).
Code Examples
package main
import (
"fmt"
"net/http"
)
func main() {
mux := http.NewServeMux()
mux.HandleFunc("GET /users/{id}", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, r.PathValue("id"))
})
mux.HandleFunc("GET /health", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNoContent)
})
http.ListenAndServe(":8080", mux)
}func mount(mux *http.ServeMux, prefix string, h http.Handler) {
mux.Handle(prefix+"/", http.StripPrefix(prefix, h))
}Common Gotchas
Registering on `DefaultServeMux` from a library surprises `main`
return a handler instead.
`GET /users/{id}` does not match `/users/{id}/`
trailing slashes are distinct unless you register both or a redirect.