Home  >  Article  >  Backend Development  >  How to Redirect 404 Errors to Index.html in a Go Static File Server?

How to Redirect 404 Errors to Index.html in a Go Static File Server?

DDD
DDDOriginal
2024-10-28 05:29:30584browse

How to Redirect 404 Errors to Index.html in a Go Static File Server?

How to handle a missing file error when using a static file server?

When using the FileServer method to serve static files from a local directory, all the assets on the root route are served correctly. For example, index.html and style.css are served without any issues for requests to myserverurl/index.html and myserverurl/styles.css. However, if a request is made to a route for which there is no corresponding file, a 404 error is returned.

To serve index.html for all such routes and render the appropriate screen, a custom handler can be created that wraps the FileServer handler.

Creating the wrapper

The wrapper handler creates a wrapper http.ResponseWriter which is passed to the FileServer handler. This wrapper response writer inspects the status code. If it finds that the status code is 404, it does not send the response to the client. Instead, it sends a redirect to /index.html.

Here is an example of how the wrapper http.ResponseWriter may look like:

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
}

The FileServer handler is wrapped using this wrapper:

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)
        }
    }
}

The wrapped handler is then registered to serve requests:

func main() {
    fs := wrapHandler(http.FileServer(http.Dir(".")))
    http.HandleFunc("/", fs)
    panic(http.ListenAndServe(":8080", nil))
}

Attempting to query a non-existing file like /a.txt3 or favicon.ico, will result in a 404 error and the request being redirected to /index.html.

The above is the detailed content of How to Redirect 404 Errors to Index.html in a Go Static File Server?. 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