gonegroni

Serving index file when route not found under Negroni


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?


Solution

  • 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))
    }