英文:
how to wrap gorilla mux func handler by yaag middleware
问题
我正在按照这个教程进行操作。http://thenewstack.io/make-a-restful-json-api-go/
router := mux.NewRouter().StrictSlash(true)
for _, route := range routes {
router.
Methods(route.Method).
Path(route.Pattern).
Name(route.Name).
Handler(route.HandlerFunc)
}
我需要使用yaag中间件来包装端点函数。
r.HandleFunc("/", middleware.HandleFunc(handler))
如何实现这个?
编辑:
我正在将其包装在Logger中并返回handler。Logger以http.Handle作为第一个参数。所以包装route.HandlerFunc不起作用。你能帮我解决这个问题吗?
handler := Logger(route.HandlerFunc, route.Name)
router.
Methods(route.Method).
Path(route.Pattern).
Name(route.Name).
Handler(handler)
英文:
I am following this tutorial. http://thenewstack.io/make-a-restful-json-api-go/
router := mux.NewRouter().StrictSlash(true)
for _, route := range routes {
router.
Methods(route.Method).
Path(route.Pattern).
Name(route.Name).
Handler(route.HandlerFunc)
}
I need to wrap the endpoint func using yaag middleware.
r.HandleFunc("/", middleware.HandleFunc(handler))
How to achieve this?
EDIT:
I am wrapping in around the Logger and returning the haddler. Logger takes first argument, as http.Handle. So wrapping the route.HandlerFunc won't work. Can you please help me here?
handler := Logger(route.HandlerFunc, route.Name)
router.
Methods(route.Method).
Path(route.Pattern).
Name(route.Name).
Handler(handler)
答案1
得分: 4
你只需要将.Handler()
替换为.HandlerFunc()
,并使用中间件包装你的处理函数,这样每个端点首先经过yaag中间件,然后再传递给你的处理函数,像这样:
router := mux.NewRouter().StrictSlash(true)
for _, route := range routes {
router.
Methods(route.Method).
Path(route.Pattern).
Name(route.Name).
HandlerFunc(middleware.HandleFunc(route.HandlerFunc)) // 在这里进行修改
}
英文:
All you have to do is substitute .Handler() by .HandlerFunc() and wrap your handler function with the middleware, so each endpoint will pass first for the yaag middleware and then to your handler function, like this:
router := mux.NewRouter().StrictSlash(true)
for _, route := range routes {
router.
Methods(route.Method).
Path(route.Pattern).
Name(route.Name).
HandlerFunc(middleware.HandleFunc(route.HandlerFunc)) // change here
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论