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:
<code class="go">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) } } }</code>
The main function can create the file server, wrap it, and register it:
<code class="go">http.HandleFunc("/o/", wrapHandler( http.StripPrefix("/o", http.FileServer(http.Dir("/test"))))) panic(http.ListenAndServe(":8181", nil))</code>
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
The above is the detailed content of How can I log 404 errors when using `http.FileServer` to serve static files in Go?. For more information, please follow other related articles on the PHP Chinese website!