diff --git a/unstable/simplerouter/router.go b/unstable/simplerouter/router.go index d65ea54..5182bd4 100644 --- a/unstable/simplerouter/router.go +++ b/unstable/simplerouter/router.go @@ -62,7 +62,16 @@ func (rg *RouteGroup) StartWithGracefulShutdown(addr string) { // http.ListenAndServe takes a Handler interface defined as: ServeHTTP(ResponseWriter, *Request) func (rg *RouteGroup) ServeHTTP(w http.ResponseWriter, r *http.Request) { - rg.mux.ServeHTTP(w, r) + var handler http.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + rg.mux.ServeHTTP(w, r) + }) + + mwlen := len(rg.global_middlewares) - 1 + for i := range rg.global_middlewares { + handler = rg.global_middlewares[mwlen-i](handler) + } + + handler.ServeHTTP(w, r) } // / Handler returns the handler to use for the given request, ... propagate call to http library @@ -96,6 +105,24 @@ func (rg *RouteGroup) PopMiddleware() Middleware { return lastMiddleware } +func (rg *RouteGroup) PushGlobalMiddleware(first Middleware, others ...Middleware) *RouteGroup { + rg.global_middlewares = append(rg.global_middlewares, first) + rg.global_middlewares = append(rg.global_middlewares, others...) + return rg +} + +func (rg *RouteGroup) PopGlobalMiddleware() Middleware { + if len(rg.global_middlewares) == 0 { + return nil + } + + lastIndex := len(rg.global_middlewares) - 1 + lastMiddleware := rg.global_middlewares[lastIndex] + rg.global_middlewares = rg.global_middlewares[:lastIndex] + + return lastMiddleware +} + // applies the array of middlewares on the handler func (rg *RouteGroup) applyMiddlewares(handler http.Handler) http.Handler { mwlen := len(rg.middlewares) - 1 // We need to start from the last element going to 0 for correct ordering diff --git a/unstable/simplerouter/types.go b/unstable/simplerouter/types.go index c17c6f2..c93acb3 100644 --- a/unstable/simplerouter/types.go +++ b/unstable/simplerouter/types.go @@ -5,7 +5,8 @@ import "net/http" type Middleware func(http.Handler) http.Handler type RouteGroup struct { - mux *http.ServeMux // A ponter to the underlying ServeMux, this allows us to call ListenAndServe on any instance - basePath string // The current path we are defining handlers on / appending to - middlewares []Middleware // Stack of middlewares that will be applied on a handler in order + mux *http.ServeMux // A ponter to the underlying ServeMux, this allows us to call ListenAndServe on any instance + basePath string // The current path we are defining handlers on / appending to + middlewares []Middleware // Stack of middlewares that will be applied on a handler in order + global_middlewares []Middleware }