How Can I Customize the 404 Error Handling for a Go Static File Server?

Mary-Kate Olsen
Release: 2024-10-28 02:09:31
Original
881 people have browsed it

How Can I Customize the 404 Error Handling for a Go Static File Server?

Customizing File Not Found Handling in Go Static File Server

When serving static files in Go using http.FileServer(), unfound files typically return a 404 status code. To customize this behavior and serve a specific page instead, we need to wrap the http.FileServer() handler.

Creating a Custom HTTP Handler Wrapper

We create a custom http.ResponseWriter wrapper (NotFoundRedirectRespWr) to intercept the status code returned by the file server handler. When the status is 404, we prevent the response from being sent and redirect the request to a specified page (in this case, /index.html).

<code class="go">type NotFoundRedirectRespWr struct {
    http.ResponseWriter // We embed http.ResponseWriter
    status              int
}

func (w *NotFoundRedirectRespWr) WriteHeader(status int) {
    w.status = status // Store the status for our own use
    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 that we successfully written it
}</code>
Copy after login

Wrapping the File Server Handler

Next, we wrap the http.FileServer() handler using our custom wrapHandler function. This function adds our custom response writer to the handler chain. If the response status is 404, we redirect to /index.html.

<code class="go">func wrapHandler(h http.Handler) http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
        nfrw := &amp;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>
Copy after login

Usage

To use our custom handler, we replace the original http.FileServer() handler with our wrapped handler in our main function:

<code class="go">func main() {
    fs := wrapHandler(http.FileServer(http.Dir(".")))
    http.HandleFunc("/", fs)
    panic(http.ListenAndServe(":8080", nil))
}</code>
Copy after login

Now, any unfound files will trigger our custom handler and redirect to /index.html. This provides a more user-friendly experience for single-page web applications.

The above is the detailed content of How Can I Customize the 404 Error Handling for a Go Static File Server?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!