Im using Gorilla/Mux for routing and want to serve the React SPA regardless of the URL path.
func main() {
fmt.Println("server running...")
hub := newHub()
go hub.run()
router := mux.NewRouter()
router.HandleFunc("/api/create", Api)
router.HandleFunc("/api/getpoll", Api)
router.HandleFunc("/api/update", Api)
router.HandleFunc("/sockets/{id}", func(w http.ResponseWriter, r
*http.Request) {
Socketme(hub, w, r)
})
// router.HandleFunc("/{rest:.*}", emberHandler)
router.PathPrefix("/").HandlerFunc(serveFile)
log.Fatal(http.ListenAndServe(":5000", router))
}
func serveFile(w http.ResponseWriter, r *http.Request) {
http.FileServer(http.Dir("./public/build")).ServeHTTP(w, r)
}
Dont want Go to give 404s the Spa should be handling these routes.
The Router exports a NotFoundHandler
field which you can set to your custom handler.
router := mux.NewRouter()
router.NotFoundHandler = MyCustom404Handler
So you could do something like:
router.NotFoundHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "./public/build/index.html")
}))
so that it always serves your index page when it would normally return a 404
So I couldnt find any workable solutions to this. So I ended up taking a different approach using mux.Subrouter found here Static file server in Golang using gorilla/mux