doubinchou4219
2018-10-24 00:12 阅读 22
已采纳

将在所有其他处理程序之前运行的中间件

I have this in main:

    router := mux.NewRouter()

    router.PathPrefix("/").HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        glog.Info("before")
    })

    router.HandleFunc("/people", person.GetMany).Methods("GET")
    router.HandleFunc("/people/{id}", person.GetOne).Methods("GET")
    router.HandleFunc("/people/{id}", person.Create).Methods("POST")
    router.HandleFunc("/people/{id}", person.Delete).Methods("DELETE")

this mean that nothing got hit except the first middleware handler, so I tried creating a new router to handle the logging:

    mux.NewRouter().PathPrefix("/").HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        glog.Info("before")
    })

but this new router doesn't get hit AND none of my other routes get hit. What should I be doing instead?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

1条回答 默认 最新

  • 已采纳
    duanan2732 duanan2732 2018-10-24 00:22

    Middleware is registered by calling Router.Use

    Sample code is here

    Your code should be:

    router.Use(func(next http.Handler) http.Handler {
        return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
            glog.Info("before")
            next.ServeHTTP(w, r)
        })
    })
    
    点赞 评论 复制链接分享

相关推荐