在http.FileServer上记录404 [英] Log 404 on http.FileServer

查看:110
本文介绍了在http.FileServer上记录404的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 http.FileServer dirPath 提供jpeg图像:

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))))

我不明白的是如何记录请求一个不存在的文件。当我向浏览器发出请求时,我可以看到 http.FileServer 返回 404页面未找到

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 http.StripPrefix() http.FileServer() 不记录HTTP 404错误。你必须扩展它们的功能以实现你想要的功能。

The http.Handlers returned by http.StripPrefix() and http.FileServer() do not log HTTP 404 errors. You have to extend their functionality in order to achieve what you want.

我们可以包装 http.Handler 值在另一个 http.Handler中由 http.StripPrefix() http.FileServer()返回 http.HandlerFunc 。一旦包装了处理程序,当然就注册包装。

We can wrap the http.Handler value returned by http.StripPrefix() or http.FileServer() in another http.Handler or http.HandlerFunc. Once you wrapped the handler, register the wrapper of course.

包装器实现将简单地称为包装器,一旦它返回,就可以检查HTTP响应状态代码。如果它是一个错误(或特别是HTTP 404 Not Found),可以正确记录它。

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.

问题是 http.ResponseWriter 不支持读取响应状态码。我们可以做的是我们也包装 http.ResponseWriter ,并且在编写状态代码时,我们会将它存储起来以备后用。

Problem is http.ResponseWriter does not support reading the response status code. What we can do is we also wrap the http.ResponseWriter and when status code is written, we will store it for later to be available.

我们的 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)
}

包装 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)
        }
    }
}



<

And the main function creating a file server, wrapping it and registering it:

http.HandleFunc("/o/", wrapHandler(
    http.StripPrefix("/o", http.FileServer(http.Dir("/test")))))
panic(http.ListenAndServe(":8181", nil))

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

Example output when requesting a non-existing file:

2015/12/01 11:47:40 Error status code: 404 when serving path: /o/sub/b.txt2

这篇关于在http.FileServer上记录404的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆