使用 http.FileServer 提供靜態文件時,記錄何時對不存在的文件發出請求通常很重要存在。雖然 http.FileServer 本身不提供此類日誌記錄,但擴展其功能可讓您實現此目標。
要包裝 http.StripPrefix 和 http.FileServer 傳回的處理程序,請建立一個新的 http.Handler 或 http.Handler。處理函數。包裝器將呼叫包裝的處理程序並檢查產生的 HTTP 回應狀態碼。如果它指示錯誤(特別是 HTTP 404 Not Found),它可以記錄該事件。
由於 http.ResponseWriter 不支援讀取回應狀態碼,請為其建立包裝器 (StatusRespWr)。這個包裝器將在寫入時儲存狀態代碼。
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 error codes
log.Printf("Error status code: %d when serving path: %s",
srw.status, r.RequestURI)
}
}
}
main函數可以建立檔案伺服器,包裝它,並註冊它:
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.txt2
免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。
Copyright© 2022 湘ICP备2022001581号-3