I'm serving jpeg images from dirPath
using http.FileServer
with:
http.Handle("/o/", http.StripPrefix(
path.Join("/o", dirPath), http.FileServer(http.Dir(dirPath))))
What I don't understand is how to log when a request is made for a file that does not exist. I can see http.FileServer
returning 404 page not found when I make a request with the browser, but not on the server console.
The
http.Handler
s returned byhttp.StripPrefix()
andhttp.FileServer()
do not log HTTP 404 errors. You have to extend their functionality in order to achieve what you want.We can wrap the
http.Handler
value returned byhttp.StripPrefix()
orhttp.FileServer()
in anotherhttp.Handler
orhttp.HandlerFunc
. Once you wrapped the handler, register the wrapper of course.The wrapper implementation will simply called the wrapped one, and once it returns, can inspect the HTTP response status code. If it is an error (or specifically HTTP 404 Not Found), can log it appropriately.
Problem is
http.ResponseWriter
does not support reading the response status code. What we can do is we also wrap thehttp.ResponseWriter
and when status code is written, we will store it for later to be available.Our
http.ResponseWriter
wrapper:And wrapping the
http.Handler
:And the main function creating a file server, wrapping it and registering it:
Example output when requesting a non-existing file: