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?
1条回答 默认 最新
- doujiyuan0211 2015-10-31 18:26关注
The
Router
type in the mux library has aNotFoundHandler
field of typehttp.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)) }
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报
悬赏问题
- ¥15 Python报错怎么解决
- ¥15 simulink如何调用DLL文件
- ¥15 关于用pyqt6的项目开发该怎么把前段后端和业务层分离
- ¥30 线性代数的问题,我真的忘了线代的知识了
- ¥15 有谁能够把华为matebook e 高通骁龙850刷成安卓系统,或者安装安卓系统
- ¥188 需要修改一个工具,懂得汇编的人来。
- ¥15 livecharts wpf piechart 属性
- ¥20 数学建模,尽量用matlab回答,论文格式
- ¥15 昨天挂载了一下u盘,然后拔了
- ¥30 win from 窗口最大最小化,控件放大缩小,闪烁问题