Im trying to serve a react-router with go, i already did it, but i'm having troubles, i think the way i did is not the correct one, or it's not complete. Im using Mux. The trouble im having is that when i push the <Link>
's in my app it changes de view correctly, but when i try to change it directly from the browser or i try to reload the page i get a 404 error
I've tried diferent ways, im actually doing this way:
func main() {
var dir = "./static"
router := mux.NewRouter()
fs := http.FileServer(http.Dir(dir))
router.PathPrefix("/").Handler(fs)
fmt.Println("Server running in port :8000")
log.Fatal(http.ListenAndServe(":8000", router))
}
I want the server to serve the same directory in all request like "/", "/example", "/example2", etc.
My guess is that you have some static content and you'd like everything else to forward to the index.html
. I had a similar problem, and my solution was to just prefix all the react-router urls with a constant so I could detect that on the backend and forward it. My code looks something like this:
router := mux.NewRouter()
router.PathPrefix("/public/").Handler(http.StripPrefix("/public/", http.FileServer(http.Dir("public"))))
router.HandleFunc("/", handleIndex).Methods("GET")
router.HandleFunc("/h/{param:.*}", handleIndex).Methods("GET")
And in my react-router I just changed all the routes from {uri}
to /h/{uri}
If you really want to forward everything to the react code without any backend checking for 404s or anything, you could do:
router := mux.NewRouter()
router.NotFoundHandler = ... // Write a function to serve the index file here
fs := http.FileServer(http.Dir(dir))
router.PathPrefix("/").Handler(fs)