Go 1.22+ 用增强版 net/http ServeMux 做方法路由与路径参数
未来之星2026-11-0514 次阅读
背景
Go 1.22 起标准库 net/http 的 ServeMux 大幅增强:支持按 HTTP 方法区分路由、在 path 里写 {name} 路径参数、用 ... 匹配余下路径。很多中小型服务可以不再引入 gin、chi 等三方框架。
方法路由与路径参数
package main
import (
"fmt"
"net/http"
)
func main() {
mux := http.NewServeMux()
// 限定 GET,并从路径提取 id
mux.HandleFunc("GET /articles/{id}", func(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id")
fmt.Fprintf(w, "article %s", id)
})
// 限定 POST
mux.HandleFunc("POST /articles", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusCreated)
w.Write([]byte("created"))
})
// 通配余下路径
mux.HandleFunc("GET /static/{path...}", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, r.PathValue("path"))
})
http.ListenAndServe(":8080", mux)
}
中间件:用普通函数包裹
标准库没有中间件链原语,但可以用闭包把 handler 包一层,逻辑清晰且不依赖框架。
func withLog(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
fmt.Printf("%s %s\n", r.Method, r.URL.Path)
next(w, r)
}
}
mux.HandleFunc("GET /articles/{id}", withLog(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "article %s", r.PathValue("id"))
}))
注意点
- 方法加路径冲突时会 panic,路由要提前规划好。
- PathValue 为空时返回空串,记得校验。
- Go 1.22 之前需要显式设置 http.Server 的路由兼容性,新版默认生效。
未
未来之星
文章作者
背景 Go 1.22 起标准库 net/http 的 ServeMux 大幅增强:支持按 HTTP 方法区分路由、在...
- 分类
- 技术
- 发布时间
- 2026-11-05
- 字数
- 约 1301 字
- 阅读
- 14 次
