How to Handle 404 Errors in Go\'s Static File Server for Single-Page Web Applications?

Patricia Arquette
Release: 2024-10-28 01:16:02
Original
147 people have browsed it

How to Handle 404 Errors in Go's Static File Server for Single-Page Web Applications?

Handling 404 Errors in a Custom File Server

In a single-page web application, it is essential to handle missing files appropriately to ensure smooth user experience. When using Go's static file server, http.FileServer(), handling 404 errors can be customized.

The default behavior of http.FileServer() is to return a 404 Not Found response for non-existent files. To redirect such requests to a custom page, such as index.html, a wrapper handle can be created.

Creating a Wrapper Response Writer

The wrapper response writer inspects the status code returned by the http.FileServer() handler. If it detects a 404, it suppresses sending the response and prepares to redirect instead.

<code class="go">type NotFoundRedirectRespWr struct {
    http.ResponseWriter // 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

The wrapper handler uses the NotFoundRedirectRespWr to detect 404 errors.

<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>
Copy after login

Usage

In the main function, the wrapped handler is used instead of the original http.FileServer() handler.

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

Result

Now, requests to non-existent files will be redirected to /index.html. The log will show:

Redirecting /a.txt3 to /index.html.
Redirecting /favicon.ico to /index.html.
Copy after login

This customization allows for flexible handling of 404 errors in static file serving, improving the user experience in single-page web applications.

The above is the detailed content of How to Handle 404 Errors in Go\'s Static File Server for Single-Page Web Applications?. 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!