Home > Backend Development > Golang > How can I log 404 errors when using `http.FileServer` to serve static files in Go?

How can I log 404 errors when using `http.FileServer` to serve static files in Go?

DDD
Release: 2024-10-31 01:42:29
Original
1017 people have browsed it

How can I log 404 errors when using `http.FileServer` to serve static files in Go?

Logging 404 Errors for Http.FileServer

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>
Copy after login

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>
Copy after login

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
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template