How to Log 404 Errors in Go\'s HTTP File Server?
Logging 404 Errors in HTTP File Server
When using http.FileServer to serve files from a directory, it's not immediately clear how to log HTTP 404 errors (file not found) on the server console. While the browser may display a "404 page not found" message, this information is not automatically logged by http.FileServer.
To address this, we need to extend the functionality of the handlers returned by both http.StripPrefix and http.FileServer. We can do this by wrapping them in custom handlers or handler functions and registering the wrappers.
Our wrapper implementation will invoke the wrapped handler. After the wrapped handler returns, the wrapper can inspect the HTTP response status code. If it indicates an error (specifically HTTP 404 Not Found), the wrapper can log this appropriately.
However, http.ResponseWriter does not support retrieving the response status code. To overcome this, we'll create a custom StatusRespWr that wraps http.ResponseWriter and stores the status code for later retrieval.
Here's the implementation of 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>
Next, we'll wrap the 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>
Finally, in the main function, we create a file server, wrap it, and register the wrapped handler:
<code class="go">http.HandleFunc("/o/", wrapHandler(http.StripPrefix("/o", http.FileServer(http.Dir("/test"))))) panic(http.ListenAndServe(":8181", nil))</code>
If a request is made for a non-existent file, the following message will be logged:
2015/12/01 11:47:40 Error status code: 404 when serving path: /o/sub/b.txt2
The above is the detailed content of How to Log 404 Errors in Go\'s HTTP File Server?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



OpenSSL, as an open source library widely used in secure communications, provides encryption algorithms, keys and certificate management functions. However, there are some known security vulnerabilities in its historical version, some of which are extremely harmful. This article will focus on common vulnerabilities and response measures for OpenSSL in Debian systems. DebianOpenSSL known vulnerabilities: OpenSSL has experienced several serious vulnerabilities, such as: Heart Bleeding Vulnerability (CVE-2014-0160): This vulnerability affects OpenSSL 1.0.1 to 1.0.1f and 1.0.2 to 1.0.2 beta versions. An attacker can use this vulnerability to unauthorized read sensitive information on the server, including encryption keys, etc.

The article explains how to use the pprof tool for analyzing Go performance, including enabling profiling, collecting data, and identifying common bottlenecks like CPU and memory issues.Character count: 159

The article discusses writing unit tests in Go, covering best practices, mocking techniques, and tools for efficient test management.

The library used for floating-point number operation in Go language introduces how to ensure the accuracy is...

Queue threading problem in Go crawler Colly explores the problem of using the Colly crawler library in Go language, developers often encounter problems with threads and request queues. �...

The article discusses managing Go module dependencies via go.mod, covering specification, updates, and conflict resolution. It emphasizes best practices like semantic versioning and regular updates.

Backend learning path: The exploration journey from front-end to back-end As a back-end beginner who transforms from front-end development, you already have the foundation of nodejs,...

The article discusses using table-driven tests in Go, a method that uses a table of test cases to test functions with multiple inputs and outcomes. It highlights benefits like improved readability, reduced duplication, scalability, consistency, and a
