Home > Backend Development > Golang > How to Redirect Frontend Routes in GoLang to Avoid 404 Errors?

How to Redirect Frontend Routes in GoLang to Avoid 404 Errors?

Patricia Arquette
Release: 2024-12-20 18:17:10
Original
823 people have browsed it

How to Redirect Frontend Routes in GoLang to Avoid 404 Errors?

Redirect GoLang to Frontend Routing

Issue Description

When accessing paths like "/my_frontend_path" directly in the browser, GoLang returns a 404 error instead of delegating the routing to the frontend React router.

Problem Analysis

The primary issue is that when accessing such paths before the React router is initialized, the server handles the request and returns the error.

Single-Server Solution

A simple server-side "Catch-all" approach can be implemented to redirect all unsupported paths to the frontend router. This approach works by returning the index.html page if the requested file does not exist, allowing the React router to handle the routing.

Code Implementation

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) {
        // If requested file exists, return it; otherwise, return index.html
        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)
                }

                // Requested file does not exist, return index.html
                r.URL.Path = "/"
            }
        }
        fs.ServeHTTP(w, r)
    })

    http.ListenAndServe(":8090", nil)
}
Copy after login

In this implementation:

  • The requested file is checked for existence.
  • If it does not exist (like "/my_frontend_path"), the request is redirected to index.html.
  • The React router in index.html then handles the "/my_frontend_path" routing.

Note

This method returns index.html for files that do not exist, which may cause issues with files like "favicon.ico". In such cases, additional checks can be added to limit the redirect only to specific extensions.

The above is the detailed content of How to Redirect Frontend Routes in GoLang to Avoid 404 Errors?. 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