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

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器