Golang 1.22+ net/http ServeMux如何记录HTTP 404/405错误?
基于Go 1.22标准库的404/405日志记录方案
针对你的需求,利用Go 1.22新增的路由特性,可以用两个极简方案分别处理405和404的日志记录,完全不需要中间件或全局兜底handler:
一、处理405(方法不允许)日志
405是针对已存在路径但HTTP方法不匹配的场景,直接给每个已定义的路径添加所有非GET方法的handler,在这些handler里完成日志记录和标准405响应:
package main import ( "log" "net/http" ) func handler1(w http.ResponseWriter, r *http.Request) { w.Write([]byte("Hello from handler1")) } func handler2(w http.ResponseWriter, r *http.Request) { w.Write([]byte("Hello from handler2")) } func main() { // 注册原有GET路由 http.HandleFunc("GET /hello/", handler1) http.HandleFunc("GET /headers/", handler2) // 定义需要处理的非GET方法列表 nonGetMethods := []string{"POST", "PUT", "DELETE", "PATCH", "OPTIONS"} // 给每个已存在路径添加非GET方法的handler for _, path := range []string{"/hello/", "/headers/"} { for _, method := range nonGetMethods { http.HandleFunc(method+" "+path, func(w http.ResponseWriter, r *http.Request) { log.Printf("[405] %s %s", r.Method, r.URL.Path) http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed) }) } } log.Fatal(http.ListenAndServe(":8080", nil)) }
二、处理404(路径不存在)日志
利用Go 1.22路由的最长匹配规则和通配符*,给所有HTTP方法注册通配符路由,这些路由会捕获所有未被具体路由匹配的请求,实现404日志记录:
在上述main函数中添加以下代码:
// 给所有HTTP方法注册通配符路由,处理404请求 allMethods := append(nonGetMethods, "GET") for _, method := range allMethods { http.HandleFunc(method+" *", func(w http.ResponseWriter, r *http.Request) { log.Printf("[404] %s %s", r.Method, r.URL.Path) http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound) }) }
方案优势
- 完全基于标准库
net/http,无第三方依赖 - 严格区分404和405场景,无需全局兜底handler
- 代码简洁直观,无需编写复杂的中间件或ResponseWriter包装
- 日志记录与响应逻辑分离,符合REST规范
内容的提问来源于stack exchange,提问作者Andrew Sirolly
相关产品推荐
相关产品推荐

