首页 > 后端开发 > Golang > 正文

如何在 Go 的 HTTP 文件服务器中记录 404 错误?

Patricia Arquette
发布: 2024-10-26 20:40:29
原创
946 人浏览过

How to Log 404 Errors in Go's HTTP File Server?

在 HTTP 文件服务器中记录 404 错误

当使用 http.FileServer 提供目录中的文件时,无法立即清楚如何记录服务器控制台上出现 HTTP 404 错误(未找到文件)。虽然浏览器可能会显示“404 页面未找到”消息,但 http.FileServer 不会自动记录此信息。

为了解决此问题,我们需要扩展 http.StripPrefix 返回的处理程序的功能和 http.FileServer。我们可以通过将它们包装在自定义处理程序或处理程序函数中并注册包装器来做到这一点。

我们的包装器实现将调用包装的处理程序。包装处理程序返回后,包装器可以检查 HTTP 响应状态代码。如果它指示错误(特别是 HTTP 404 Not Found),包装器可以适当地记录此错误。

但是,http.ResponseWriter 不支持检索响应状态代码。为了克服这个问题,我们将创建一个自定义 StatusRespWr 来包装 http.ResponseWriter 并存储状态代码以供以后检索。

这是 StatusRespWr 的实现:

<code class="go">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)
}</code>
登录后复制

接下来,我们' ll 包装 http.Handler:

<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>
登录后复制

最后,在 main 函数中,我们创建一个文件服务器,包装它,并注册包装的处理程序:

<code class="go">http.HandleFunc("/o/", wrapHandler(http.StripPrefix("/o", http.FileServer(http.Dir("/test")))))
panic(http.ListenAndServe(":8181", nil))</code>
登录后复制

如果请求是为不存在的文件创建的,将记录以下消息:

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

以上是如何在 Go 的 HTTP 文件服务器中记录 404 错误?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!