dongyuan8312 2015-10-31 17:21
浏览 43
已采纳

在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?

  • 写回答

1条回答 默认 最新

  • doujiyuan0211 2015-10-31 18:26
    关注

    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))
    } 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么