huzaib sayyed
huzaib sayyed

Reputation: 11

404 Not Working With React App on Golang Server

My Redirection works perfectly when running reactjs app in development environment (npm run dev), proper redirect to home. But when i serving same app on golang, after npm run build, redirection doesn't work.

App.jsx

import {
  Route,
  createBrowserRouter,
  createRoutesFromElements,
  RouterProvider,
  Navigate,
} from "react-router-dom";
import HomePage from "./pages/Home/HomePage";
import MainLayout from "./layouts/MainLayout";
import { useGlobal } from "./GlobalState";
import PodPage from "./pages/Pods/PodPage";

const App = () => {
  const { isClusterConnected } = useGlobal();

  const router = createBrowserRouter(
    createRoutesFromElements(
      <>
        <Route path="/" element={<MainLayout />}>
          <Route
            index
            element={
              isClusterConnected ? <Navigate to="/pods" /> : <HomePage />
            }
          />
          <Route path="*" element={<Navigate to="/" replace />} />
          <Route
            path="/pods"
            element={!isClusterConnected ? <Navigate to="/" /> : <PodPage />}
          />
        </Route>
      </>
    )
  );

  return <RouterProvider router={router} />;
};

export default App;

but same running on golang, after building react app and embedding it in golang, it always give 404 if i have a path in url, localhost:8080 works, but when i refresh on localhost:8080/pods or /non-existent then it gives 404 error.

main.go

//go:embed dist/*
var distFS embed.FS

func main() {
    r := mux.NewRouter()

    k8sApiRouter := r.PathPrefix("/api/k8s").Subrouter()
    r.HandleFunc("/api/k8s/set-client", api.Setk8sClient).Methods("POST")
    r.HandleFunc("/api/k8s/cluster-connected", api.ClusterConnected).Methods("GET")
    r.HandleFunc("/api/k8s/disconnect", api.SetClientSetToNil).Methods("GET")
    r.HandleFunc("/execute", executeCommand)
    k8sApi.RegisterK8sRouters(k8sApiRouter)

    // Serve your ReactJS frontend (assuming it's in a "build" directory)
    // Create a subdirectory in the embedded file system
    subFS, err := fs.Sub(distFS, "dist")
    if err != nil {
        fmt.Println("Failed to locate embedded files:", err)
        return
    }
    r.PathPrefix("/").Handler(http.FileServer(http.FS(subFS)))

    handler := config.CORS.Handler(r)

    port := ":8080"
    fmt.Println("Server started on " + port)
    http.Handle("/", handler)
    http.ListenAndServe(port, nil)
}

func executeCommand(w http.ResponseWriter, r *http.Request) {
    if r.Method == "OPTIONS" {
        return
    }

    if r.Method != "POST" {
        http.Error(w, "Invalid request method", http.StatusMethodNotAllowed)
        return
    }

    cmd, err := io.ReadAll(r.Body)
    if err != nil {
        http.Error(w, "Error reading command", http.StatusBadRequest)
        return
    }

    output, err := exec.Command("sh", "-c", string(cmd)).CombinedOutput()
    if err != nil {
        http.Error(w, "Failed to execute command", http.StatusInternalServerError)
        return
    }

    w.Header().Set("Content-Type", "text/plain")
    w.Write(output)
}

Here is clear 404 issues, lets say my react app runs localhost:3000, if i refresh on any path it takes me to home page. but when i serve react app in golang, go to localhost:8080 it works, programmatically navigation also works, but when i click on refresh browser button, it gives 404, refreshing on localhost:8080 takes me to homepage, but any path in it gives 404

I tried this in golang

// Custom NotFound handler
    r.NotFoundHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        http.Redirect(w, r, "/", http.StatusSeeOther)
    })

not sure if the fix is in react app or golang project.

Upvotes: 1

Views: 79

Answers (1)

huzaib sayyed
huzaib sayyed

Reputation: 11

To address this, you need to modify the handler to check for the file's existence and serve index.html if the file does not exist. Here’s the updated version of your Go server code:

//go:embed dist/*
var distFS embed.FS

func main() {
    r := mux.NewRouter()

    // Create a subdirectory in the embedded file system
    subFS, err := fs.Sub(distFS, "dist")
    if err != nil {
        fmt.Println("Failed to locate embedded files:", err)
        return
    }

    // Serve static files and index.html for frontend routes
    r.PathPrefix("/").HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        filePath := path.Clean(r.URL.Path)
        if filePath == "/" {
            filePath = "index.html"
        } else {
            filePath = strings.TrimPrefix(filePath, "/")
        }

        file, err := subFS.Open(filePath)
        if os.IsNotExist(err) || filePath == "index.html" {
            http.ServeFile(w, r, "dist/index.html")
            return
        } else if err != nil {
            http.Error(w, "Internal Server Error", http.StatusInternalServerError)
            return
        }
        defer file.Close()

        http.FileServer(http.FS(subFS)).ServeHTTP(w, r)
    })

    handler := config.CORS.Handler(r)

    port := ":8080"
    fmt.Println("Server started on " + port)
    http.Handle("/", handler)
    http.ListenAndServe(port, nil)
}

Upvotes: 0

Related Questions