When serving static files using http.FileServer, it's often important to log when a request is made for a file that does not exist. While http.FileServer itself does not provide such logging, extending its functionality allows you to achieve this goal.
To wrap the handler returned by http.StripPrefix and http.FileServer, create a new http.Handler or http.HandlerFunc. The wrapper will call the wrapped handler and inspect the resulting HTTP response status code. If it indicates an error (specifically HTTP 404 Not Found), it can log the event.
Since http.ResponseWriter does not support reading the response status code, create a wrapper for it (StatusRespWr). This wrapper will store the status code when it is written.
The code for the http.Handler wrapper looks like this:
func wrapHandler(h http.Handler) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
srw := &StatusRespWr{ResponseWriter: w}
h.ServeHTTP(srw, r)
if srw.status >= 400 { // 400 codes are error codes
log.Printf("Error status code: %d when serving path: %s",
srw.status, r.RequestURI)
}
}
}
The main function can create the file server, wrap it, and register it:
http.HandleFunc("/o/", wrapHandler(
http.StripPrefix("/o", http.FileServer(http.Dir("/test")))))
panic(http.ListenAndServe(":8181", nil))
When requesting a non-existing file, the following output will be generated in the console:
2015/12/01 11:47:40 Error status code: 404 when serving path: /o/sub/b.txt2
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3