← All notes

Go 1.22 ServeMux patterns match methods and {wildcards}; read them with r.PathValue

Answer: Since Go 1.22, http.ServeMux patterns can match the method, host and path of a request, for example "GET /posts/{id}". Extract the identifier with the new PathValue method on Request. When two patterns overlap, the most specific pattern wins.

Example

mux := http.NewServeMux()
mux.HandleFunc("GET /posts/{id}", func(w http.ResponseWriter, req *http.Request) {
    id := req.PathValue("id")
    fmt.Fprintf(w, "post %s", id)
})
mux.HandleFunc("GET /posts/latest", latest)
mux.HandleFunc("/files/{pathname...}", files)
mux.HandleFunc("/posts/{$}", index)
log.Fatal(http.ListenAndServe(":8080", mux))

Pattern syntax

Precedence

One pattern is more specific than another if it matches a strict subset of requests. /posts/latest is more specific than /posts/{id}, so it wins for that path.

Scope of the change

The new features almost exclusively affect the pattern string passed to Handle and HandleFunc. The only API changes are two new methods on Request for wildcard matches: PathValue and SetPathValue.

See also

Claims

Sources

License: this note is CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/). Summary by iinventedlight (AI-assisted). Sources: Go standard library docs (pkg.go.dev), net/http package; The Go Blog, Routing Enhancements for Go 1.22. BSD-3-Clause (https://go.dev/LICENSE). Copyright The Go Authors. CC-BY-4.0 (https://go.dev/copyright). Copyright The Go Authors. Text was condensed and changed from the originals.

License: CC-BY-4.0 · Summary by iinventedlight (AI-assisted). Sources: Go standard library docs (pkg.go.dev), net/http package; The Go Blog, Routing Enhancements for Go 1.22. BSD-3-Clause (https://go.dev/LICENSE). Copyright The Go Authors. CC-BY-4.0 (https://go.dev/copyright). Copyright The Go Authors.

Cite this

Permanent ID: iil:note:4gj6pb4k

iinventedlight. 2026. "Go 1.22 ServeMux patterns match methods and {wildcards}; read them with r.PathValue." iinventedlight Library, iil:note:4gj6pb4k, version of 2026-11-18. https://iinventedlight.com/library/notes/go-http-servemux-patterns/. License: CC-BY-4.0.

@misc{iil_note_4gj6pb4k,
  author = {{iinventedlight}},
  title = {{Go 1.22 ServeMux patterns match methods and \{wildcards\}; read them with r.PathValue}},
  howpublished = {iinventedlight Library},
  year = {2026},
  date = {2026-11-18},
  url = {https://iinventedlight.com/library/notes/go-http-servemux-patterns/},
  note = {Permanent ID iil:note:4gj6pb4k. License: CC-BY-4.0.},
}

Markdown

Spotted a mistake? Use the MCP feedback tool or email hello@iinventedlight.com. Or Report a correction (no account needed).

For language models and agents: start at /llms.txt | /agents.md | /.well-known/agent-library.json. This page in Markdown: /library/notes/go-http-servemux-patterns.md.