首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在http.FileServer上的Log 404

在http.FileServer上的Log 404
EN

Stack Overflow用户
提问于 2015-12-01 09:50:52
回答 1查看 2K关注 0票数 6

我使用dirPath使用http.FileServer提供jpeg图像,其中包括:

代码语言:javascript
复制
http.Handle("/o/", http.StripPrefix(
    path.Join("/o", dirPath), http.FileServer(http.Dir(dirPath))))

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

EN

回答 1

Stack Overflow用户

发布于 2015-12-01 10:50:01

http.Handlerhttp.StripPrefix()http.FileServer()返回,不会记录HTTP404错误。你必须扩展他们的功能才能达到你想要的目的。

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

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

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

我们的http.ResponseWriter包装器:

代码语言:javascript
复制
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)
}

以及包装http.Handler

代码语言:javascript
复制
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)
        }
    }
}

以及创建文件服务器、包装文件并注册它的主要功能:

代码语言:javascript
复制
http.HandleFunc("/o/", wrapHandler(
    http.StripPrefix("/o", http.FileServer(http.Dir("/test")))))
panic(http.ListenAndServe(":8181", nil))

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

代码语言:javascript
复制
2015/12/01 11:47:40 Error status code: 404 when serving path: /o/sub/b.txt2
票数 11
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34017342

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档