ServeMux Method And Wildcard Patterns

Route HTTP methods and path segments with Go 1.22 ServeMux: method-scoped patterns, {id} wildcards through PathValue, and automatic 404/405 for misses.

GoData Fetching

Code

snippet
package main

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

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

	// Go 1.22 增强模式:方法 + 路径段,{id} 是单段 wildcard
	mux.HandleFunc("GET /tasks/{id}", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "get task %s", r.PathValue("id"))
	})
	mux.HandleFunc("POST /tasks", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintln(w, "created task")
	})
	// {path...} 吞掉剩余所有段
	mux.HandleFunc("GET /files/{path...}", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "rest of path: %s", r.PathValue("path"))
	})

	for _, c := range []struct{ method, target string }{
		{"GET", "/tasks/42"},
		{"POST", "/tasks"},
		{"GET", "/files/a/b/c.txt"},
		{"DELETE", "/tasks/42"},
		{"GET", "/tasks"},
	} {
		rec := httptest.NewRecorder()
		mux.ServeHTTP(rec, httptest.NewRequest(c.method, c.target, nil))
		fmt.Printf("%s %s -> %d %s\n", c.method, c.target, rec.Code, strings.TrimSpace(rec.Body.String()))
	}
}

Reading the snippet

Count the function main as the entire surface area of ServeMux Method And Wildcard Patterns.

The one repetition in this snippet is the loop for _, c := range []struct{ method, target string }.

Statements that matter

mux.ServeHTTP(rec, httptest.NewRequest(c.method, c.target, nil))

Interactive Tools for This Topic

FAQ

How do you run ServeMux Method And Wildcard Patterns?
Run it as a complete program — compile or interpret the file directly; there is nothing to install first.