1
votes

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

1 Answers

4
votes

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
}