go - Serve a file when no route is matched with Gorilla? -
i'm using gorilla mux web server.
i define bunch of routes, if no route matched, want serve index.html file.
func (mgr *apimgr) instantiaterestrtr() *mux.router { mgr.prestrtr = mux.newrouter().strictslash(true) mgr.prestrtr.pathprefix("/api/").handler(http.stripprefix("/api/", http.fileserver(http.dir(mgr.fullpath+"/docsui")))) _, route := range mgr.restroutes { var handler http.handler handler = logger(route.handlerfunc, route.name) mgr.prestrtr.methods(route.method) .path(route.pattern) .name(route.name) .handler(handler) } // here want catch unmatched routes, , serve '/site/index.html` file. // how can this? return mgr.prestrtr }
you don't need override 404 behaviour. use pathprefix
catch-all route, adding after other routes.
func main() { var entry string var static string var port string flag.stringvar(&entry, "entry", "./index.html", "the entrypoint serve.") flag.stringvar(&static, "static", ".", "the directory serve static files from.") flag.stringvar(&port, "port", "8000", "the `port` listen on.") flag.parse() r := mux.newrouter() // note: in larger application, we'd extract our route-building logic our handlers // package, given coupling between them. // it's important before catch-all route ("/") api := r.pathprefix("/api/v1/").subrouter() api.handlefunc("/users", getusershandler).methods("get") // serve static assets directly. r.pathprefix("/dist").handler(http.fileserver(http.dir(static))) // catch-all: serve our javascript application's entry-point (index.html). r.pathprefix("/").handlerfunc(indexhandler(entry)) srv := &http.server{ handler: handlers.logginghandler(os.stdout, r), addr: "127.0.0.1:" + port, // practice: enforce timeouts servers create! writetimeout: 15 * time.second, readtimeout: 15 * time.second, } log.fatal(srv.listenandserve()) } func indexhandler(entrypoint string) func(w http.responsewriter, r *http.request) { fn := func(w http.responsewriter, r *http.request) { http.servefile(w, r, entrypoint) } return http.handlerfunc(fn) }
shameless plug: blogged on here: http://elithrar.github.io/article/vue-react-ember-server-golang/
Comments
Post a Comment