Handling 404 Errors in Go Static File Servers
When serving static files using a Go server, unfound file requests typically result in a 404 Not Found error. To customize this behavior and redirect users to a specific page, such as index.html, a custom handler can be implemented.
Creating a Custom Handler
The default FileServer handler provided by the Go standard library does not support error customization. To implement a custom handler, wrap it and monitor the response status code. If a 404 error is detected, replace the response with a redirect.
Here's a sample response writer that inspects the status code:
<code class="go">type NotFoundRedirectRespWr struct { http.ResponseWriter // Embedded http.ResponseWriter status int } func (w *NotFoundRedirectRespWr) WriteHeader(status int) { w.status = status if status != http.StatusNotFound { w.ResponseWriter.WriteHeader(status) } } func (w *NotFoundRedirectRespWr) Write(p []byte) (int, error) { if w.status != http.StatusNotFound { return w.ResponseWriter.Write(p) } return len(p), nil // Lie about successful writing }</code>
Wrapping the File Server Handler
The wrapped handler function calls the original handler and checks the status code. If it's a 404, it redirects to index.html.
<code class="go">func wrapHandler(h http.Handler) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { nfrw := &NotFoundRedirectRespWr{ResponseWriter: w} h.ServeHTTP(nfrw, r) if nfrw.status == 404 { log.Printf("Redirecting %s to index.html.", r.RequestURI) http.Redirect(w, r, "/index.html", http.StatusFound) } } }</code>
Using the Custom Handler
In the main function, register the wrapped handler at the root URL:
<code class="go">func main() { fs := wrapHandler(http.FileServer(http.Dir("."))) http.HandleFunc("/", fs) panic(http.ListenAndServe(":8080", nil)) }</code>
Log Output
Attempting to access non-existent files should generate the following logs:
2017/11/14 14:10:21 Redirecting /a.txt3 to /index.html. 2017/11/14 14:10:21 Redirecting /favicon.ico to /index.html.
Note: All unfound files, including favicon.ico, will be redirected to index.html. If this is not desired, you can add exceptions as needed.
Full Code Sample
Visit the Go Playground for the complete code example:
[https://go.dev/play/p/51SEMfTIM8s](https://go.dev/play/p/51SEMfTIM8s)
The above is the detailed content of How can I customize 404 error responses and redirect users to a specific page in a Go static file server?. For more information, please follow other related articles on the PHP Chinese website!