diff --git a/echo.go b/echo.go index 73ee5673..552caac8 100644 --- a/echo.go +++ b/echo.go @@ -24,6 +24,7 @@ type ( prefix string middleware []Middleware head Handler + pristineHead Handler maxParam *int notFoundHandler HandlerFunc httpErrorHandler HTTPErrorHandler @@ -190,7 +191,16 @@ func New() (e *Echo) { return NewContext(nil, nil, e) } e.router = NewRouter(e) - e.head = e.router.Handle(nil) + e.middleware = []Middleware{e.router} + e.head = e.router.Handle(HandlerFunc(func(c Context) error { + return c.Handle(c) + })) + e.pristineHead = e.head + + // e.head = HandlerFunc(func(c Context) error { + // return c.Handle(c) + // }) + // e.router.Handle(e.head) //---------- // Defaults @@ -282,14 +292,25 @@ func (e *Echo) Debug() bool { return e.debug } -// Use adds handler to the middleware chain. -func (e *Echo) Use(middleware ...Middleware) { +// Pre adds middleware to the chain which is runs before router. +func (e *Echo) Pre(middleware ...Middleware) { e.middleware = append(e.middleware, middleware...) - m := append(e.middleware, e.router) + e.head = e.pristineHead // Chain middleware - for i := len(m) - 1; i >= 0; i-- { - e.head = m[i].Handle(e.head) + for i := len(e.middleware) - 1; i >= 0; i-- { + e.head = e.middleware[i].Handle(e.head) + } +} + +// Use adds middleware to the chain which is runs after router. +func (e *Echo) Use(middleware ...Middleware) { + e.middleware = append(e.middleware, middleware...) + e.head = e.pristineHead + + // Chain middleware + for i := len(e.middleware) - 1; i >= 0; i-- { + e.head = e.middleware[i].Handle(e.head) } } diff --git a/router.go b/router.go index 0bed809f..e3f82227 100644 --- a/router.go +++ b/router.go @@ -47,12 +47,12 @@ func NewRouter(e *Echo) *Router { } } -func (r *Router) Handle(h Handler) Handler { +func (r *Router) Handle(next Handler) Handler { return HandlerFunc(func(c Context) error { method := c.Request().Method() path := c.Request().URL().Path() r.Find(method, path, c) - return c.Handle(c) + return next.Handle(c) }) }