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.
Code
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
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Nginx Location Block TesterTest any URL path against Nginx location blocks using authentic Nginx precedence (= exact, ^~ prefix, regex ~ and ~*, and longest prefix) with trace output.Accept Header ParserParse an Accept header into media ranges with their quality values and specificity, sorted by preference for content negotiation debugging.Basic & Bearer Auth Header ToolEncode and decode HTTP Authorization Basic and Bearer headers locally with UTF-8 Base64 validation and automatic JWT claim and expiry inspection.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.