我使用dirPath使用http.FileServer提供jpeg图像,其中包括:
http.Handle("/o/", http.StripPrefix(
path.Join("/o", dirPath), http.FileServer(http.Dir(dirPath))))我不明白的是,当对不存在的文件发出请求时,如何进行日志记录。当我使用浏览器发出请求时,我可以看到http.FileServer返回404页面找不到,但在服务器控制台上没有返回。
发布于 2015-12-01 10:50:01
http.Handler由http.StripPrefix()和http.FileServer()返回,不会记录HTTP404错误。你必须扩展他们的功能才能达到你想要的目的。
我们可以将http.StripPrefix()或http.FileServer()返回的http.StripPrefix()值包装在另一个http.Handler或http.HandlerFunc中。一旦包装好处理程序,当然要注册包装器。
包装器实现将简单地调用包装的实现,一旦它返回,就可以检查HTTP响应状态代码。如果它是一个错误(或者特别是HTTP 404找不到),可以适当地记录它。
问题是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)
}以及包装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)
}
}
}以及创建文件服务器、包装文件并注册它的主要功能:
http.HandleFunc("/o/", wrapHandler(
http.StripPrefix("/o", http.FileServer(http.Dir("/test")))))
panic(http.ListenAndServe(":8181", nil))请求不存在的文件时的示例输出:
2015/12/01 11:47:40 Error status code: 404 when serving path: /o/sub/b.txt2https://stackoverflow.com/questions/34017342
复制相似问题