首页  >  文章  >  后端开发  >  在 Go 中使用“http.FileServer”提供文件时如何记录 404 错误?

在 Go 中使用“http.FileServer”提供文件时如何记录 404 错误?

Patricia Arquette
Patricia Arquette原创
2024-10-26 19:39:29746浏览

How can I log 404 errors when serving files with `http.FileServer` in Go?

记录 Http.FileServer 的 404 错误

使用 http.FileServer 提供文件时,记录所请求文件的实例可能很有用不存在,导致 404 状态代码。但是,默认的 http.FileServer 处理程序不提供此功能。

扩展功能

要记录 404 错误,您可以扩展 http.FileServer 的功能处理程序。这可以通过使用自定义 http.Handler 或 http.HandlerFunc 包装处理程序来实现。

包装处理程序

包装处理程序将调用原始 http.FileServer处理程序,然后检查 HTTP 响应状态代码。如果是错误(特别是 404 Not Found),它可以适当地记录错误。

响应状态代码包装器

由于 http.ResponseWriter 不支持读取直接响应状态代码,您可以创建一个包装器,在设置时存储状态代码。

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

func (w *StatusRespWr) WriteHeader(status int) {
    w.status = status // Store the status for later use
    w.ResponseWriter.WriteHeader(status)
}</code>

Handler Wrapper

将响应状态代码包装器地方,您可以创建一个记录错误的处理程序包装器:

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

注册包装的处理程序

最后,您可以将包装的处理程序注册为您的路由中的路由HTTP 服务器:

<code class="go">http.HandleFunc("/o/", wrapHandler(http.FileServer(http.Dir("/test"))))</code>

示例输出

当请求不存在的文件时,包装的处理程序将在控制台记录一条错误消息:

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

以上是在 Go 中使用“http.FileServer”提供文件时如何记录 404 错误?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn