I’m playing around with net/http after reading about the routing upgrades in 1.22, the goal here is to only use stdlib, so I'm intentionally avoiding frameworks and routers that are not part of the stdlib such as gin or gorilla/chi.
...
func main() {
mux := http.NewServeMux()
mux.Handle("GET /hello/{$}", handler1)
mux.Handle("GET /headers/{$}", handler2)
http.ListenAndServe(port, mux)
}
does what I expect it to do:
GET requests to /hello/ or /hello route to handler 1
GET requests to /headers/ or /headers route to handler 2
POST requests to handled paths return a HTTP 405
unhandled paths return a HTTP 404
However, in the case of a 404 or 405 these are simply responses and are not recorded in stdout, is there a simple way to also add log these bad requests without adding extra handlers/middleware?
Writing a handler as a catch all such as mux.Handle("/", badHandler) would require extra complexity to deal with 404 vs 405, if there is an alternative I'd like to avoid it.
building middleware to spy on a responseWriter, checking the statusCode, and logging on 404/405 seems like it would also potentially work depending on what is made public by the http package (though I haven't looked into this option yet), but is more complex of a solution I would otherwise hope is available.