How to convert old middleware func to new middleware func

149 Views Asked by At

I have this existing library call:

func Policy(quota *Quota, options ...*Options) func(resp http.ResponseWriter, req *http.Request) {
    o := newOptions(options)
    if o.Disabled {
        return func(resp http.ResponseWriter, req *http.Request) {}
    }
   /// ...
}

we used to use Martini but are updating to Mux since Martini is no longer maintained. The old Martini router called it like so:

m := &martini.ClassicMartini{bm, r}

m.Use(throttle.Policy(&throttle.Quota{
    Limit:  10000,
    Within: 24 * time.Hour,
}))

but I need to update it for mux middleware like so:

r := mux.NewRouter()
r.Use(func(h http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        fun := throttle.Policy(&throttle.Quota{
            Limit:  10000,
            Within: 24 * time.Hour,
        })
        fun(w,r)
        h.ServeHTTP(w,r);
    })
});

the above "seems to be correct" but I really am not sure. It would be nice to be able to check the return value of fun() to see if I should continue calling the remaining middleware. This is a flaw I am not sure how to solve with golang.

0

There are 0 best solutions below