I am using Golang, Negroni, and Gorilla mux for a web api server. I have my api routes under /api and I am using Negroni to serve static files from my /public directory using urls under /. I would like to serve my index.html file (containing a single page javascript application) not only if it is requested by name or as the index file, but also if the request would otherwise result in a 404 because it doesn't correspond to a route or a file in the /public directory. This is so that those URLs will load the webapp which will transition to the correct route (client side javascript history/pushState) or else give a not found error if that resource doesn't exist. Is there a way to get Negroni's static middleware or Gorilla mux to do this?
Asked
Active
Viewed 1,038 times
1 Answers
4
The Router
type in the mux library has a NotFoundHandler
field of type http.Handler
. This would allow you to handle a unmatched route as you see fit:
// NotFoundHandler overrides the default not found handler
func NotFoundHandler(w http.ResponseWriter, r *http.Request) {
// You can use the serve file helper to respond to 404 with
// your request file.
http.ServeFile(w, r, "public/index.html")
}
func main() {
r := mux.NewRouter()
r.NotFoundHandler = http.HandlerFunc(NotFoundHandler)
// Register other routes or setup negroni
log.Fatal(http.ListenAndServe(":8080", r))
}

Ben Campbell
- 4,298
- 2
- 29
- 33
-
1Yep, this is the way to go and how I've done it for my Ember (and now React) applications. You can additionally mount a separate router/mux for your `/api` routes and configure your `NotFoundHandler` there to write out a 404 with a JSON body for any `/api/
` routes that don't exist. – elithrar Nov 02 '15 at 00:01 -
1Be sure to new routers in this case. A `Router` returned by a `Subrouter()` function call will not call a `NotFoundHandler` added to that Subrouter. – Ben Campbell Nov 02 '15 at 00:49