Home >Backend Development >Golang >How to Redirect Frontend Routes in GoLang to Avoid 404 Errors?
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.
The primary issue is that when accessing such paths before the React router is initialized, the server handles the request and returns the error.
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.
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) }
In this implementation:
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!