Home >Backend Development >Golang >How to Handle 404 Errors for Frontend Routes in a Go Server?

How to Handle 404 Errors for Frontend Routes in a Go Server?

Barbara Streisand
Barbara StreisandOriginal
2024-12-24 14:39:15200browse

How to Handle 404 Errors for Frontend Routes in a Go Server?

Handling 404 Errors for Unresolved Frontend Routes in Go

In a server setup with both a React front-end app and a Go API, accessing a non-existent frontend route (e.g., http://localhost:8090/my_frontend_path) results in a 404 error. To address this, there are several approaches, one of which is utilizing a "catch-all" strategy on the server.

"Catch-All" Approach

This method ensures that for any path not explicitly handled elsewhere, the server returns the index.html page. As the frontend application is loaded with index.html, it can then handle the routing itself.

A straightforward implementation in Go:

const FSPATH = "./build/"

func main() {
    fs := http.FileServer(http.Dir(FSPATH))

    http.HandleFunc("/my_api", func(w http.ResponseWriter, _ *http.Request) { w.Write([]byte("API CALL")) })
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        // Return index.html if the requested file doesn't exist
        if r.URL.Path != "/" {
            fullPath := FSPATH + strings.TrimPrefix(path.Clean(r.URL.Path), "/")
            _, err := os.Stat(fullPath)
            if err != nil {
                if !os.IsNotExist(err) {
                    panic(err)
                }
                r.URL.Path = "/"
            }
        }
        fs.ServeHTTP(w, r)
    })
    http.ListenAndServe(":8090", nil)
}

By checking for the file's existence and falling back to index.html if it's not found, this code ensures that the React router takes over and handles the routing for all paths. This approach provides a simple server-side solution to redirect any unresolved routes to the frontend.

The above is the detailed content of How to Handle 404 Errors for Frontend Routes in a Go 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