@@ -16,11 +16,13 @@ type Route struct {
16
16
type Router struct {
17
17
routes map [string ][]* Route
18
18
notFoundHandler Handler
19
+ middlewares map [string ][]Middleware
19
20
}
20
21
21
22
func New () * Router {
22
23
return & Router {
23
- routes : make (map [string ][]* Route ),
24
+ routes : make (map [string ][]* Route ),
25
+ middlewares : make (map [string ][]Middleware ),
24
26
}
25
27
}
26
28
@@ -47,12 +49,25 @@ func (r *Router) find(method, path string) []Handler {
47
49
if matches , params := route .match (path ); matches {
48
50
c := NewContext (nil , nil )
49
51
c .params = params
50
- return route .Handlers
52
+ return r . applyMiddleware ( route .Handlers , method )
51
53
}
52
54
}
53
55
return nil
54
56
}
55
57
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
+
56
71
func RouterHandler (router * Router ) func (ctx * fasthttp.RequestCtx ) {
57
72
return func (ctx * fasthttp.RequestCtx ) {
58
73
path := string (ctx .Path ())
@@ -67,7 +82,7 @@ func RouterHandler(router *Router) func(ctx *fasthttp.RequestCtx) {
67
82
for _ , route := range router .routes [method ] {
68
83
if matches , params := route .match (path ); matches {
69
84
c := NewContext (ctx , nil ).WithParams (params )
70
- for _ , h := range handlers {
85
+ for _ , h := range router . applyMiddleware ( route . Handlers , method ) {
71
86
err := h (c )
72
87
if err != nil {
73
88
ctx .Error (err .Error (), fasthttp .StatusInternalServerError )
@@ -80,7 +95,7 @@ func RouterHandler(router *Router) func(ctx *fasthttp.RequestCtx) {
80
95
81
96
c := NewContext (ctx , params )
82
97
83
- for _ , h := range handlers {
98
+ for _ , h := range router . applyMiddleware ( handlers , method ) {
84
99
err := h (c )
85
100
if err != nil {
86
101
ctx .Error (err .Error (), fasthttp .StatusInternalServerError )
0 commit comments