douqiao8370 2017-06-21 19:31
浏览 85
已采纳

使用Gorilla MUX和Negroni的子路由中间件

I'm trying to add a middleware only on some routes. I wrote this code:

func main() {
  router := mux.NewRouter().StrictSlash(false)

  admin_subrouter := router.PathPrefix("/admin").Subrouter()

  //handlers.CombinedLoggingHandler comes from gorilla/handlers
  router.PathPrefix("/admin").Handler(negroni.New(
    negroni.Wrap(handlers.CombinedLoggingHandler(os.Stdout, admin_subrouter)),
  ))

  admin_subrouter.HandleFunc("/articles/new", articles_new).Methods("GET")
  admin_subrouter.HandleFunc("/articles", articles_index).Methods("GET")
  admin_subrouter.HandleFunc("/articles", articles_create).Methods("POST")

  n := negroni.New()
  n.UseHandler(router)
  http.ListenAndServe(":3000", n)

}

I expect to see request logs only for paths with prefix /admin. I do see a log line when I do "GET /admin", but not when I do "GET /admin/articles/new". I tried by brute force other combinations but I can't get it. What's wrong with my code?

I saw other ways, like wrapping the HandlerFunc on each route definition, but I wanted to do it once for a prefix or a subrouter.

The logging middleware I'm using there is for testing, maybe an Auth middleware makes more sense, but I just wanted to make it work.

Thanks!

  • 写回答

1条回答 默认 最新

  • duangekui7451 2017-06-21 20:24
    关注

    Issue is the way you create an sub routes /admin. Complete reference code is here https://play.golang.org/p/zb_79oHJed

    // Admin
    adminBase := mux.NewRouter()
    router.PathPrefix("/admin").Handler(negroni.New(
        // This logger only applicable to /admin routes
        negroni.HandlerFunc(justTestLogger),
        // add your handlers here which is only appilcable to `/admin` routes
        negroni.Wrap(adminBase),
    ))
    
    adminRoutes := adminBase.PathPrefix("/admin").Subrouter()
    adminRoutes.HandleFunc("/articles/new", articleNewHandler).Methods("GET")
    

    Now, access these URLs. You will see logs only for /admin sub routes.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥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的速度时间图像)我想问线路信息是什么