在http.FileServer上记录404

hen*_*dry 2 http go http-status-code-404

我正在dirPath使用jpeg图像http.FileServer:

http.Handle("/o/", http.StripPrefix(
    path.Join("/o", dirPath), http.FileServer(http.Dir(dirPath))))
Run Code Online (Sandbox Code Playgroud)

我不明白的是如何在对不存在的文件发出请求时进行记录.我可以看到当我使用浏览器发出请求时找不到http.FileServer返回的404页面,但是在服务器控制台上没有找到.

icz*_*cza 7

http.Handler返回的s http.StripPrefix()并且http.FileServer()不记录HTTP 404错误.您必须扩展其功能才能实现您的目标.

我们可以包装或在另一个或中http.Handler返回的值.包装处理程序后,当然要注册包装器.http.StripPrefix()http.FileServer()http.Handlerhttp.HandlerFunc

包装器实现将简单地调用包装的实现,一旦返回,就可以检查HTTP响应状态代码.如果是错误(或者特别是HTTP 404 Not Found),可以适当地记录它.

问题是http.ResponseWriter不支持读取响应状态代码.我们可以做的是我们还包装了http.ResponseWriter当写入状态代码时,我们将它存储起来供以后使用.

我们的http.ResponseWriter包装:

type StatusRespWr struct {
    http.ResponseWriter // We embed http.ResponseWriter
    status int
}

func (w *StatusRespWr) WriteHeader(status int) {
    w.status = status // Store the status for our own use
    w.ResponseWriter.WriteHeader(status)
}
Run Code Online (Sandbox Code Playgroud)

并包装http.Handler:

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 the error codes
            log.Printf("Error status code: %d when serving path: %s",
                srw.status, r.RequestURI)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

主要功能是创建文件服务器,包装并注册它:

http.HandleFunc("/o/", wrapHandler(
    http.StripPrefix("/o", http.FileServer(http.Dir("/test")))))
panic(http.ListenAndServe(":8181", nil))
Run Code Online (Sandbox Code Playgroud)

请求不存在的文件时的示例输出:

2015/12/01 11:47:40 Error status code: 404 when serving path: /o/sub/b.txt2
Run Code Online (Sandbox Code Playgroud)

  • 天哪,希望它减轻痛苦! (3认同)