Go core
Browse topics

HTTP routing with ServeMux patterns

Version
1.27
Since
1.22
Review
Draft

Summary#

http.ServeMux patterns can name a method and capture path segments. {id} matches one segment, and {path...} matches the rest. Handlers read captures with PathValue. The most specific matching pattern wins, with a compatibility exception for conflicting patterns where only one specifies a host.

Syntax#

go
mux := http.NewServeMux()
mux.HandleFunc("GET /items/{id}", showItem)
id := r.PathValue("id")

Example#

go
package main

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

func main() {
	mux := http.NewServeMux()
	mux.HandleFunc("GET /items/{id}", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprint(w, "item ", r.PathValue("id"))
	})
	mux.HandleFunc("GET /items/new", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprint(w, "new item form")
	})
	mux.HandleFunc("GET /files/{path...}", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprint(w, "file ", r.PathValue("path"))
	})

	for _, call := range []string{
		"GET /items/42",
		"GET /items/new",
		"GET /files/docs/a.txt",
		"DELETE /items/42",
		"GET /items/42/extra",
	} {
		method, path, _ := strings.Cut(call, " ")
		recorder := httptest.NewRecorder()
		mux.ServeHTTP(recorder, httptest.NewRequest(method, path, nil))
		fmt.Println(call, "->", recorder.Code, strings.TrimSpace(recorder.Body.String()))
	}
}

Expected output#

Text
GET /items/42 -> 200 item 42
GET /items/new -> 200 new item form
GET /files/docs/a.txt -> 200 file docs/a.txt
DELETE /items/42 -> 405 Method Not Allowed
GET /items/42/extra -> 404 404 page not found

Common mistakes#

Registering conflicting patterns such as GET / and /index.html panics. A GET pattern also matches HEAD. A pattern ending in / matches a subtree. Use a suffix of /{$} to match only the path ending in that slash.

Version applicability#

Method patterns, wildcard patterns and PathValue make the example require Go 1.22 or later. GODEBUG=httpmuxgo121=1 at startup restores the old routing behavior. With the old behavior, inspect the method and parse the path inside the handler.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0