Varun Gupta
Varun Gupta

Reputation: 1457

how to wrap gorilla mux func handler by yaag middleware

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)

Upvotes: 1

Views: 945

Answers (1)

Yandry Pozo
Yandry Pozo

Reputation: 5123

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
}

Upvotes: 4

Related Questions