如何通过Yaag中间件包装Gorilla Mux函数处理程序

huangapple go评论71阅读模式
英文:

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
}

huangapple
  • 本文由 发表于 2016年10月28日 07:45:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/40295887.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定