-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmiddlewares.go
More file actions
31 lines (26 loc) · 779 Bytes
/
middlewares.go
File metadata and controls
31 lines (26 loc) · 779 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package api
import (
"github.com/gorilla/mux"
"net/http"
)
type Middleware interface {
Middleware(handler http.Handler) http.Handler
}
type MiddlewareChain struct {
Middlewares []Middleware
}
func (c *MiddlewareChain) Use(mwf ...mux.MiddlewareFunc) {
for _, fn := range mwf {
c.Middlewares = append(c.Middlewares, fn)
}
}
// Apply takes an input http.Handler and applies the middleware chain over a single http.Handler
// These middlewares are chained in the order they are registered
// If middleware A is registered earlier than B, then execution will be A => B => handler
func (c *MiddlewareChain) Apply(handler http.Handler) http.Handler {
cur := handler
for i := len(c.Middlewares) - 1; i >= 0; i-- {
cur = c.Middlewares[i].Middleware(cur)
}
return cur
}