Route requests with ServeMux method patterns
Route requests with ServeMux method patterns
ServeMux chooses a handler using the request method, host and path. Go 1.22 introduced method-aware patterns and named path wildcards. Use a private mux (http.NewServeMux) rather than the process-wide default to make routes explicit. These examples use the modern routing behavior (not GODEBUG=httpmuxgo121=1).
package main
import ( "fmt" "net/http" "net/http/httptest" "strings")
func probe(h http.Handler, method, path, body string) *httptest.ResponseRecorder { w := httptest.NewRecorder() h.ServeHTTP(w, httptest.NewRequest(method, path, strings.NewReader(body))) return w}func main() { m := http.NewServeMux() m.HandleFunc("GET /items/{id}", func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, r.PathValue("id")) }) for _, method := range []string{"GET", "POST"} { w := probe(m, method, "/items/42", "") fmt.Println(w.Code) if w.Code == 200 { fmt.Println(w.Body.String()) } else { fmt.Println(w.Header().Get("Allow")) } }}GET patterns also match HEAD. POST to the same path does not match this route and receives 405 with Allow. A missing path instead returns 404. PathValue reads a matched wildcard; a wildcard represents a segment, not a validated identifier. HEAD body suppression is a server behavior; a recorder alone does not model all wire semantics.
Expected output:
20042405GET, HEADPrefer the more specific pattern
package main
import ( "fmt" "net/http" "net/http/httptest" "strings")
func probe(h http.Handler, method, path, body string) *httptest.ResponseRecorder { w := httptest.NewRecorder() h.ServeHTTP(w, httptest.NewRequest(method, path, strings.NewReader(body))) return w}func main() { m := http.NewServeMux() m.HandleFunc("GET /items/{id}", func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "item") }) m.HandleFunc("GET /items/latest", func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "latest") }) for _, p := range []string{"/items/latest", "/items/42", "/other"} { w := probe(m, "GET", p, "") fmt.Println(w.Code, strings.TrimSpace(w.Body.String())) }}Specificity depends on the set of requests matched, not registration order. Conflicting patterns without a more-specific winner generally panic during registration (there is a host-specific compatibility exception). A trailing slash pattern can match a subtree and cause redirects; use {$} to match its end exactly. Do not treat route selection as authorization.
Expected output:
200 latest200 item404 404 page not foundTry it locally
Register POST /jobs and return 202; show status for POST and GET.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
HTTP servers 02: Route requests with ServeMux method patterns
Check the lesson objective before moving on.
Which pattern also matches HEAD?
How does ServeMux choose between /items/latest and /items/{id}?