How to Log 404 Errors When Using HTTP File Server?

Barbara Streisand
Release: 2024-10-27 03:12:30
Original
797 people have browsed it

How to Log 404 Errors When Using HTTP File Server?

Log 404 Status on Missing Files with HTTP File Server

When serving files using http.FileServer, requests for non-existent files can return a 404 status code without being logged on the server console. This can make it challenging to track and troubleshoot missing files.

Solution

To log HTTP 404 errors, enhance the functionality of the handlers returned by http.StripPrefix() and http.FileServer():

  1. Wrap the original handler in a custom handler or handler function.
  2. Override the WriteHeader() method in a new StatusRespWr struct that wraps http.ResponseWriter. This allows us to capture the HTTP status code.

The wrapped handler will call the original handler and log HTTP 404 or higher error codes after receiving the response. The example code below demonstrates a complete implementation:

<code class="go">type StatusRespWr struct {
    http.ResponseWriter
    status int
}

func (w *StatusRespWr) WriteHeader(status int) {
    w.status = status
    w.ResponseWriter.WriteHeader(status)
}

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 {
            log.Printf("Error status code: %d when serving path: %s", srw.status, r.RequestURI)
        }
    }
}

func main() {
    http.HandleFunc("/o/", wrapHandler(
        http.StripPrefix("/o", http.FileServer(http.Dir("/test")))))
    panic(http.ListenAndServe(":8181", nil))
}</code>
Copy after login

When a non-existent file is requested, the wrapped handler will log the following error:

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 to Log 404 Errors When Using HTTP File Server?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template