Routing with ServeMux patterns

suggest change

Before Go 1.22, http.ServeMux could only match fixed paths and path prefixes (see Serving content using ServeMux). To route GET /items/42 and DELETE /items/42 to different handlers you had to check r.Method yourself and parse 42 out of r.URL.Path, or use a third-party router.

Go 1.22 extended the patterns that ServeMux understands. A pattern can now include:

The REST APIs article shows these patterns in a CRUD service. This article goes deeper: the full syntax, how the mux picks between patterns that overlap, redirects, middleware, testing and mounting sub-routers.

All examples drive the mux with net/http/httptest, so you can run them without opening a port.

Methods and wildcards

The general form of a pattern is:

[METHOD ][HOST]/[PATH]

All parts are optional except the / that starts the path. The method is separated from the rest with a space. Inside a handler, r.PathValue(name) returns the text matched by the wildcard {name}:

package main

import (
	"fmt"
	"io"
	"net/http"
	"net/http/httptest"
	"strings"
)

func main() {
	mux := http.NewServeMux()

	mux.HandleFunc("GET /items", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintln(w, "list items")
	})
	mux.HandleFunc("POST /items", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintln(w, "create item")
	})
	mux.HandleFunc("GET /items/{id}", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "get item %s\n", r.PathValue("id"))
	})
	mux.HandleFunc("DELETE /items/{id}", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "delete item %s\n", r.PathValue("id"))
	})

	srv := httptest.NewServer(mux)
	defer srv.Close()

	do := func(method, path string) {
		req, _ := http.NewRequest(method, srv.URL+path, nil)
		resp, err := http.DefaultClient.Do(req)
		if err != nil {
			panic(err)
		}
		body, _ := io.ReadAll(resp.Body)
		resp.Body.Close()
		allow := resp.Header.Get("Allow")
		if allow != "" {
			allow = "Allow: " + allow
		}
		fmt.Printf("%-6s %-12s %d %-18s %s\n", method, path, resp.StatusCode,
			strings.TrimSpace(string(body)), allow)
	}

	do("GET", "/items")
	do("POST", "/items")
	do("GET", "/items/42")
	do("HEAD", "/items/42")
	do("DELETE", "/items/42")
	do("PUT", "/items/42")
	do("GET", "/items/42/x")
	do("GET", "/users")
}
GET    /items       200 list items
POST   /items       200 create item
GET    /items/42    200 get item 42
HEAD   /items/42    200
DELETE /items/42    200 delete item 42
PUT    /items/42    405 Method Not Allowed Allow: DELETE, GET, HEAD
GET    /items/42/x  404 404 page not found
GET    /users       404 404 page not found

Things to notice:

Wildcard names must be valid Go identifiers, and a wildcard must be a whole segment: /items/{id} is valid, /items/item-{id} and /files/{name}.json are not.

Rest wildcards, subtrees and {$}

Three more forms control how much of the path a pattern matches:

The handler prints r.Pattern, which holds the pattern that matched (added in Go 1.23):

package main

import (
	"fmt"
	"net/http"
	"net/http/httptest"
	"strings"
)

func show(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "pattern=%q", r.Pattern)
	for _, name := range []string{"bucket", "object", "path"} {
		if v := r.PathValue(name); v != "" {
			fmt.Fprintf(w, " %s=%q", name, v)
		}
	}
}

func main() {
	mux := http.NewServeMux()
	mux.HandleFunc("/{$}", show)                      // only "/"
	mux.HandleFunc("/", show)                         // everything else
	mux.HandleFunc("/static/", show)                  // subtree
	mux.HandleFunc("/b/{bucket}/o/{object...}", show) // rest of the path
	mux.HandleFunc("/files/{path...}", show)
	mux.HandleFunc("/docs/{$}", show) // "/docs/" but not deeper

	for _, path := range []string{
		"/",
		"/about",
		"/static/css/site.css",
		"/b/photos/o/2024/trip/beach.jpg",
		"/b/photos/o/",
		"/files/a%2Fb/c.txt",
		"/docs/",
		"/docs/intro",
	} {
		rec := httptest.NewRecorder()
		mux.ServeHTTP(rec, httptest.NewRequest("GET", path, nil))
		fmt.Printf("%-33s %d %s\n", path, rec.Code, strings.TrimSpace(rec.Body.String()))
	}
}
/                                 200 pattern="/{$}"
/about                            200 pattern="/"
/static/css/site.css              200 pattern="/static/"
/b/photos/o/2024/trip/beach.jpg   200 pattern="/b/{bucket}/o/{object...}" bucket="photos" object="2024/trip/beach.jpg"
/b/photos/o/                      200 pattern="/b/{bucket}/o/{object...}" bucket="photos"
/files/a%2Fb/c.txt                200 pattern="/files/{path...}" path="a/b/c.txt"
/docs/                            200 pattern="/docs/{$}"
/docs/intro                       200 pattern="/"

The {$} wildcard fixes an old annoyance: a home page registered as "/" used to also serve every unknown URL, so you had to check r.URL.Path == "/" and call http.NotFound yourself. Register "GET /{$}" for the home page instead, and let "/" be an explicit catch-all only if you want one.

A {path...} wildcard can match an empty string (/b/photos/o/). Paths are unescaped segment by segment, so %2F in /files/a%2Fb/c.txt doesn't split segments when matching, but the value you get from PathValue is unescaped: "a/b/c.txt". If you use such a value as a file name, validate it; Application security covers path traversal.

Precedence: the most specific pattern wins

Unlike older routers, the order in which you register patterns doesn't matter. When several patterns match a request, ServeMux picks the most specific one. Pattern A is more specific than B if A matches a strict subset of the requests B matches:

package main

import (
	"fmt"
	"net/http"
	"net/http/httptest"
)

func main() {
	mux := http.NewServeMux()
	for _, p := range []string{
		"/posts/",
		"GET /posts/{id}",
		"GET /posts/latest",
		"POST /posts/{id}",
		"GET /posts/{id}/comments/{cid}",
		"api.example.com/posts/{id}",
	} {
		mux.HandleFunc(p, func(w http.ResponseWriter, r *http.Request) {
			fmt.Fprint(w, r.Pattern)
		})
	}

	for _, req := range []struct{ method, target string }{
		{"GET", "/posts/latest"},
		{"GET", "/posts/7"},
		{"POST", "/posts/7"},
		{"GET", "/posts/7/comments/3"},
		{"GET", "/posts/7/comments/3/likes"},
		{"DELETE", "/posts/7"},
		{"GET", "http://api.example.com/posts/7"},
	} {
		rec := httptest.NewRecorder()
		mux.ServeHTTP(rec, httptest.NewRequest(req.method, req.target, nil))
		fmt.Printf("%-6s %-31s -> %s\n", req.method, req.target, rec.Body.String())
	}
}
GET    /posts/latest                   -> GET /posts/latest
GET    /posts/7                        -> GET /posts/{id}
POST   /posts/7                        -> POST /posts/{id}
GET    /posts/7/comments/3             -> GET /posts/{id}/comments/{cid}
GET    /posts/7/comments/3/likes       -> /posts/
DELETE /posts/7                        -> /posts/
GET    http://api.example.com/posts/7  -> api.example.com/posts/{id}

DELETE /posts/7 got the /posts/ handler, not a 405. A 405 is only sent when no pattern at all matches the request. The same applies to a catch-all "/": once you register one, the mux never sends a 405 or its own 404, because the catch-all matches everything.

Conflicts panic at registration

If two patterns overlap and neither is more specific than the other, the mux can't decide between them, so Handle and HandleFunc panic when you register the second one. Invalid patterns panic too. That sounds harsh, but it happens at startup, every time, and the message explains the problem. Here we recover from the panics to show several of them:

package main

import (
	"fmt"
	"net/http"
	"regexp"
	"strings"
)

var registeredAt = regexp.MustCompile(` \(registered at [^)]*\)`)

// register returns "ok" or the panic message without the file:line noise
func register(mux *http.ServeMux, pattern string) (msg string) {
	defer func() {
		if r := recover(); r != nil {
			msg = registeredAt.ReplaceAllString(fmt.Sprint(r), "")
		}
	}()
	mux.HandleFunc(pattern, func(http.ResponseWriter, *http.Request) {})
	return "ok"
}

func main() {
	tests := [][]string{
		{"/users/{id}", "/users/{name}"},
		{"/{a}/b", "/a/{b}"},
		{"/posts/latest", "POST /posts/{id}"},
		{"GET /", "/index.html"},
		{"/files/{rest...}", "/files/"},
		{"/a/b{x}"},
		{"/{path...}/edit"},
	}
	for _, patterns := range tests {
		mux := http.NewServeMux()
		for _, p := range patterns {
			msg := register(mux, p)
			fmt.Printf("%-18s %s\n", p, strings.ReplaceAll(msg, "\n", "\n    "))
		}
	}
}
/users/{id}        ok
/users/{name}      pattern "/users/{name}" conflicts with pattern "/users/{id}":
    /users/{name} matches the same requests as /users/{id}
/{a}/b             ok
/a/{b}             pattern "/a/{b}" conflicts with pattern "/{a}/b":
    /a/{b} and /{a}/b both match some paths, like "/a/b".
    But neither is more specific than the other.
    /a/{b} matches "/a/bx", but /{a}/b doesn't.
    /{a}/b matches "/ax/b", but /a/{b} doesn't.
/posts/latest      ok
POST /posts/{id}   pattern "POST /posts/{id}" conflicts with pattern "/posts/latest":
    POST /posts/{id} matches fewer methods than /posts/latest, but has a more general path pattern
GET /              ok
/index.html        pattern "/index.html" conflicts with pattern "GET /":
    /index.html matches more methods than GET /, but has a more specific path pattern
/files/{rest...}   ok
/files/            pattern "/files/" conflicts with pattern "/files/{rest...}":
    /files/ matches the same requests as /files/{rest...}
/a/b{x}            parsing "/a/b{x}": at offset 3: bad wildcard segment (must start with '{')
/{path...}/edit    parsing "/{path...}/edit": at offset 1: {...} wildcard not at end

The /posts/latest vs POST /posts/{id} case surprises people: POST /posts/latest matches both, and one pattern is more specific in method while the other is more specific in path. The fix is to make one of them strictly more specific, for example by giving both a method: GET /posts/latest and POST /posts/{id} don't overlap at all.

In a real program the panic message also includes the file and line where each pattern was registered. Because the mux checks every pattern when it's added, a test that just builds your router (calls your routes() function) catches conflicts before you deploy.

Host patterns

A pattern that starts with something other than / (or a method) begins with a host. The mux matches it against the request's Host header, after stripping the port:

package main

import (
	"fmt"
	"net/http"
	"net/http/httptest"
)

func main() {
	mux := http.NewServeMux()
	show := func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, r.Pattern) }
	mux.HandleFunc("/", show)
	mux.HandleFunc("GET /{id}", show)
	mux.HandleFunc("api.example.com/", show)
	mux.HandleFunc("GET admin.example.com/{$}", show)

	for _, req := range []struct{ host, path string }{
		{"example.com", "/"},
		{"example.com", "/7"},
		{"api.example.com", "/7"},
		{"api.example.com:8443", "/7"},
		{"admin.example.com", "/"},
		{"admin.example.com", "/7"},
		{"API.example.com", "/7"},
	} {
		r := httptest.NewRequest("GET", req.path, nil)
		r.Host = req.host // what the client sent in the Host header
		rec := httptest.NewRecorder()
		mux.ServeHTTP(rec, r)
		fmt.Printf("%-21s %-3s -> %s\n", req.host, req.path, rec.Body.String())
	}
}
example.com           /   -> /
example.com           /7  -> GET /{id}
api.example.com       /7  -> api.example.com/
api.example.com:8443  /7  -> api.example.com/
admin.example.com     /   -> GET admin.example.com/{$}
admin.example.com     /7  -> GET /{id}
API.example.com       /7  -> GET /{id}

api.example.com/ and GET /{id} both match GET api.example.com/7, and by the general rule they would conflict (one is more specific in host, the other in method and path). For backwards compatibility, the pattern with a host wins. Host matching is case-sensitive, so API.example.com falls through to the patterns without a host.

Trailing-slash redirects and path cleaning

If you register a subtree such as /images/ (or /files/{path...}) and a request comes in for /images, the mux redirects it to /images/. It also redirects paths that contain ., .. or repeated slashes to their cleaned form. Since Go 1.26 these redirects use 307 Temporary Redirect. Earlier versions used 301 Moved Permanently, which browsers cache forever and which lets clients change a POST into a GET. A 307 keeps the method and the body.

package main

import (
	"fmt"
	"net/http"
	"net/http/httptest"
)

func main() {
	mux := http.NewServeMux()
	ok := func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, r.Pattern) }
	mux.HandleFunc("/images/", ok)
	mux.HandleFunc("/files/{path...}", ok)
	mux.HandleFunc("/docs/", ok)
	mux.HandleFunc("/docs", ok) // registered separately: no redirect
	mux.HandleFunc("POST /upload/", ok)

	for _, req := range []struct{ method, path string }{
		{"GET", "/images"},
		{"GET", "/images?size=small"},
		{"GET", "/files"},
		{"GET", "/docs"},
		{"POST", "/upload"},
		{"GET", "/images//cat.png"},
		{"GET", "/images/a/../cat.png"},
	} {
		rec := httptest.NewRecorder()
		mux.ServeHTTP(rec, httptest.NewRequest(req.method, req.path, nil))
		res := rec.Body.String()
		if loc := rec.Header().Get("Location"); loc != "" {
			res = "Location: " + loc
		}
		fmt.Printf("%-4s %-22s %d %s\n", req.method, req.path, rec.Code, res)
	}
}
GET  /images                307 Location: /images/
GET  /images?size=small     307 Location: /images/?size=small
GET  /files                 307 Location: /files/
GET  /docs                  200 /docs
POST /upload                307 Location: /upload/
GET  /images//cat.png       307 Location: /images/cat.png
GET  /images/a/../cat.png   307 Location: /images/cat.png

The query string is preserved. To serve /docs directly instead of redirecting, register it as a separate pattern, as above. Redirects of subtree roots also happen for patterns with methods (POST /upload/), so a client posting to /upload gets a 307 and resends the body to /upload/.

r.Pattern and r.PathValue in middleware

Middleware that wraps the whole mux runs before routing, so at that point r.Pattern is empty and r.PathValue returns "". ServeMux stores the match in the same *http.Request it passes on, though, so after next.ServeHTTP returns, the middleware can read them. That's how you get per-route metrics with labels like GET /users/{id} instead of one label per user ID:

package main

import (
	"fmt"
	"maps"
	"net/http"
	"net/http/httptest"
	"slices"
	"sync"
)

type statusRecorder struct {
	http.ResponseWriter
	status int
}

func (s *statusRecorder) WriteHeader(code int) {
	s.status = code
	s.ResponseWriter.WriteHeader(code)
}

type routeStats struct {
	mu     sync.Mutex
	counts map[string]int
}

// Middleware counts requests per route pattern, not per URL,
// so /users/1 and /users/2 end up in the same bucket.
func (s *routeStats) Middleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		before := r.Pattern
		sr := &statusRecorder{ResponseWriter: w, status: http.StatusOK}
		next.ServeHTTP(sr, r)
		// ServeMux stores the matched pattern in r, so it's visible now
		route := r.Pattern
		if route == "" {
			route = "(no match)"
		}
		fmt.Printf("%-10s before=%q after=%q id=%q\n", r.URL.Path, before, r.Pattern, r.PathValue("id"))
		s.mu.Lock()
		s.counts[fmt.Sprintf("%s -> %d", route, sr.status)]++
		s.mu.Unlock()
	})
}

func main() {
	mux := http.NewServeMux()
	mux.HandleFunc("GET /users/{id}", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "user %s", r.PathValue("id"))
	})

	stats := &routeStats{counts: map[string]int{}}
	h := stats.Middleware(mux)

	for _, path := range []string{"/users/1", "/users/2", "/nope"} {
		h.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("GET", path, nil))
	}
	for _, route := range slices.Sorted(maps.Keys(stats.counts)) {
		fmt.Printf("%-26s %d\n", route, stats.counts[route])
	}
}
/users/1   before="" after="GET /users/{id}" id="1"
/users/2   before="" after="GET /users/{id}" id="2"
/nope      before="" after="" id=""
(no match) -> 404          1
GET /users/{id} -> 200     2

If middleware needs the path values before calling the handler (for example to check that the user may access {org}), it can't wrap the whole mux; wrap individual handlers instead, as in the next section. More middleware patterns are in HTTP server middleware.

SetPathValue for middleware and tests

r.SetPathValue(name, value) sets the value that r.PathValue(name) returns. It has two main uses:

Here's a handler and a middleware that turns /users/me into the current user's ID:

package users

import (
	"fmt"
	"net/http"
	"strconv"
)

func GetUser(w http.ResponseWriter, r *http.Request) {
	id, err := strconv.Atoi(r.PathValue("id"))
	if err != nil {
		http.Error(w, "invalid user id", http.StatusBadRequest)
		return
	}
	fmt.Fprintf(w, "user %d", id)
}

// ResolveMe replaces the {id} value "me" with the logged-in user's id,
// so /users/me and /users/17 are served by the same handler.
func ResolveMe(next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		if r.PathValue("id") == "me" {
			r.SetPathValue("id", currentUserID(r))
		}
		next(w, r)
	}
}

func currentUserID(r *http.Request) string {
	return "17" // in a real app: read it from the session
}

And their tests. TestGetUser calls the handler directly, so nothing parses the path: SetPathValue provides the value the mux would have set. TestRoutes goes through a real mux to test the pattern and the middleware together:

package users

import (
	"net/http"
	"net/http/httptest"
	"testing"
)

// Calls the handler directly, without a ServeMux.
func TestGetUser(t *testing.T) {
	tests := []struct {
		id   string
		code int
		body string
	}{
		{"42", 200, "user 42"},
		{"abc", 400, "invalid user id\n"},
	}
	for _, tt := range tests {
		req := httptest.NewRequest("GET", "/users/"+tt.id, nil)
		req.SetPathValue("id", tt.id)
		rec := httptest.NewRecorder()
		GetUser(rec, req)
		if rec.Code != tt.code || rec.Body.String() != tt.body {
			t.Errorf("id=%s: got %d %q, want %d %q", tt.id, rec.Code, rec.Body, tt.code, tt.body)
		}
	}
}

// Goes through a real ServeMux to test the pattern and the middleware.
func TestRoutes(t *testing.T) {
	mux := http.NewServeMux()
	mux.HandleFunc("GET /users/{id}", ResolveMe(GetUser))

	for _, tt := range []struct{ path, want string }{
		{"/users/5", "user 5"},
		{"/users/me", "user 17"},
	} {
		rec := httptest.NewRecorder()
		mux.ServeHTTP(rec, httptest.NewRequest("GET", tt.path, nil))
		t.Logf("%s -> %d %s", tt.path, rec.Code, rec.Body)
		if rec.Body.String() != tt.want {
			t.Errorf("%s: got %q, want %q", tt.path, rec.Body, tt.want)
		}
	}
}
$ go test -v .
=== RUN   TestGetUser
--- PASS: TestGetUser (0.00s)
=== RUN   TestRoutes
    users_test.go:41: /users/5 -> 200 user 5
    users_test.go:41: /users/me -> 200 user 17
--- PASS: TestRoutes (0.00s)
PASS
ok  	example.com/users	1.210s

Test handlers directly when you're testing their logic, and through the mux (the same one your main uses) when you're testing routing. Third-party routers each have their own way of injecting URL parameters into a test request; with ServeMux it's one method call.

Mounting sub-muxes with http.StripPrefix

A ServeMux is an http.Handler, so you can mount one mux inside another. Combine it with http.StripPrefix so the inner mux can be written as if it served from /:

package main

import (
	"fmt"
	"net/http"
	"net/http/httptest"
)

func show(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "pattern=%q path=%q id=%q org=%q",
		r.Pattern, r.URL.Path, r.PathValue("id"), r.PathValue("org"))
}

func main() {
	// a self-contained API, written as if it lived at "/"
	api := http.NewServeMux()
	api.HandleFunc("GET /users/{id}", show)
	api.HandleFunc("GET /{$}", show)

	// the members API needs the org from the parent pattern
	members := http.NewServeMux()
	members.HandleFunc("GET /members/{id}", show)

	root := http.NewServeMux()
	root.Handle("/api/v1/", http.StripPrefix("/api/v1", api))
	root.Handle("/orgs/{org}/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		org := r.PathValue("org")
		// StripPrefix takes a fixed string, so build it from the wildcard value
		h := http.StripPrefix("/orgs/"+org, members)
		h.ServeHTTP(w, r)
	}))

	for _, path := range []string{
		"/api/v1/users/7",
		"/api/v1/",
		"/api/v1",
		"/orgs/acme/members/3",
	} {
		rec := httptest.NewRecorder()
		root.ServeHTTP(rec, httptest.NewRequest("GET", path, nil))
		res := rec.Body.String()
		if loc := rec.Header().Get("Location"); loc != "" {
			res = "Location: " + loc
		}
		fmt.Printf("%-21s %d %s\n", path, rec.Code, res)
	}
}
/api/v1/users/7       200 pattern="GET /users/{id}" path="/users/7" id="7" org=""
/api/v1/              200 pattern="GET /{$}" path="/" id="" org=""
/api/v1               307 Location: /api/v1/
/orgs/acme/members/3  200 pattern="GET /members/{id}" path="/members/3" id="3" org=""

This works well for a fixed prefix such as /api/v1. Note that:

When the prefix contains wildcards, or when you want a group of routes to share middleware, register the full patterns on a single mux instead. A small helper is enough:

package main

import (
	"fmt"
	"net/http"
	"net/http/httptest"
	"strings"
)

// group registers routes under a common prefix and middleware,
// all on the same ServeMux, so every wildcard stays visible.
type group struct {
	mux    *http.ServeMux
	prefix string
	mw     []func(http.Handler) http.Handler
}

func (g *group) Handle(pattern string, h http.Handler) {
	method, path, ok := strings.Cut(pattern, " ")
	if !ok {
		method, path = "", pattern
	}
	for i := len(g.mw) - 1; i >= 0; i-- {
		h = g.mw[i](h)
	}
	g.mux.Handle(strings.TrimSpace(method+" "+g.prefix+path), h)
}

func (g *group) HandleFunc(pattern string, h http.HandlerFunc) {
	g.Handle(pattern, h)
}

func requireOrgMember(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if r.Header.Get("X-User") == "" {
			http.Error(w, "unauthorized", http.StatusUnauthorized)
			return
		}
		next.ServeHTTP(w, r)
	})
}

func main() {
	mux := http.NewServeMux()
	mux.HandleFunc("GET /{$}", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprint(w, "home")
	})

	orgs := &group{mux: mux, prefix: "/orgs/{org}", mw: []func(http.Handler) http.Handler{requireOrgMember}}
	orgs.HandleFunc("GET /members/{id}", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "org=%s member=%s (pattern %q)", r.PathValue("org"), r.PathValue("id"), r.Pattern)
	})
	orgs.HandleFunc("POST /members", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "added member to %s", r.PathValue("org"))
	})

	for _, req := range []struct{ method, path, user string }{
		{"GET", "/", ""},
		{"GET", "/orgs/acme/members/3", "alice"},
		{"POST", "/orgs/acme/members", "alice"},
		{"GET", "/orgs/acme/members/3", ""},
	} {
		r := httptest.NewRequest(req.method, req.path, nil)
		if req.user != "" {
			r.Header.Set("X-User", req.user)
		}
		rec := httptest.NewRecorder()
		mux.ServeHTTP(rec, r)
		fmt.Printf("%-4s %-21s %d %s\n", req.method, req.path, rec.Code, strings.TrimSpace(rec.Body.String()))
	}
}
GET  /                     200 home
GET  /orgs/acme/members/3  200 org=acme member=3 (pattern "GET /orgs/{org}/members/{id}")
POST /orgs/acme/members    200 added member to acme
GET  /orgs/acme/members/3  401 unauthorized

All routes live in one mux, so conflicts across groups are still detected at startup, r.Pattern contains the full pattern, and every wildcard is visible to the handlers and to the group's middleware.

Restoring the old behaviour: GODEBUG=httpmuxgo121

The new syntax changed the meaning of some old patterns. In Go 1.21 {id} was ordinary text, so /items/{id} matched only the literal path /items/{id}. Go 1.22 and later also reject patterns that used to be accepted, such as /a{x}, and unescape patterns and paths segment by segment.

Programs whose go.mod says go 1.21 or older get the old behaviour automatically. For newer modules, you can restore it with the httpmuxgo121 GODEBUG setting, either in the environment or with a //go:debug httpmuxgo121=1 line before package main:

package main

import (
	"fmt"
	"net/http"
	"net/http/httptest"
	"strings"
)

func main() {
	mux := http.NewServeMux()
	mux.HandleFunc("/items/{id}", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "id=%q", r.PathValue("id"))
	})
	for _, path := range []string{"/items/42", "/items/{id}"} {
		rec := httptest.NewRecorder()
		mux.ServeHTTP(rec, httptest.NewRequest("GET", path, nil))
		fmt.Printf("%-12s %d %s\n", path, rec.Code, strings.TrimSpace(rec.Body.String()))
	}
}
$ go run main.go
/items/42    200 id="42"
/items/{id}  200 id="{id}"
$ GODEBUG=httpmuxgo121=1 go run main.go
/items/42    404 404 page not found
/items/{id}  200 id=""

With the old matching, /items/42 is not found, and PathValue always returns "". In 1.21 mode a pattern like "GET /items" doesn't panic either: it's silently treated as a host GET and never matches. The setting is read once at startup and applies to every ServeMux in the program. Use it only as a temporary bridge while you fix the patterns.

When you still need a third-party router

For most services the standard ServeMux is now enough. Reach for a router such as chi or gorilla/mux when you need:

Summary

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents