@@ -16,11 +16,13 @@ type Route struct {
1616type Router struct {
1717 routes map [string ][]* Route
1818 notFoundHandler Handler
19+ middlewares map [string ][]Middleware
1920}
2021
2122func New () * Router {
2223 return & Router {
23- routes : make (map [string ][]* Route ),
24+ routes : make (map [string ][]* Route ),
25+ middlewares : make (map [string ][]Middleware ),
2426 }
2527}
2628
@@ -47,12 +49,25 @@ func (r *Router) find(method, path string) []Handler {
4749 if matches , params := route .match (path ); matches {
4850 c := NewContext (nil , nil )
4951 c .params = params
50- return route .Handlers
52+ return r . applyMiddleware ( route .Handlers , method )
5153 }
5254 }
5355 return nil
5456}
5557
58+ func (r * Router ) applyMiddleware (handlers []Handler , method string ) []Handler {
59+ for i := len (r .middlewares [method ]) - 1 ; i >= 0 ; i -- {
60+ middleware := r.middlewares [method ][i ]
61+ for j := len (handlers ) - 1 ; j >= 0 ; j -- {
62+ handler := handlers [j ]
63+ handlers [j ] = func (ctx * Context ) error {
64+ return middleware .Handle (ctx , handler )
65+ }
66+ }
67+ }
68+ return handlers
69+ }
70+
5671func RouterHandler (router * Router ) func (ctx * fasthttp.RequestCtx ) {
5772 return func (ctx * fasthttp.RequestCtx ) {
5873 path := string (ctx .Path ())
@@ -67,7 +82,7 @@ func RouterHandler(router *Router) func(ctx *fasthttp.RequestCtx) {
6782 for _ , route := range router .routes [method ] {
6883 if matches , params := route .match (path ); matches {
6984 c := NewContext (ctx , nil ).WithParams (params )
70- for _ , h := range handlers {
85+ for _ , h := range router . applyMiddleware ( route . Handlers , method ) {
7186 err := h (c )
7287 if err != nil {
7388 ctx .Error (err .Error (), fasthttp .StatusInternalServerError )
@@ -80,7 +95,7 @@ func RouterHandler(router *Router) func(ctx *fasthttp.RequestCtx) {
8095
8196 c := NewContext (ctx , params )
8297
83- for _ , h := range handlers {
98+ for _ , h := range router . applyMiddleware ( handlers , method ) {
8499 err := h (c )
85100 if err != nil {
86101 ctx .Error (err .Error (), fasthttp .StatusInternalServerError )
0 commit comments