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

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

Patricia Arquette
Patricia ArquetteOriginal
2024-10-28 01:16:02198browse

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>

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>

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>

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.

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!

Statement:
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