-
Notifications
You must be signed in to change notification settings - Fork 0
/
midsimple.go
88 lines (75 loc) · 2.26 KB
/
midsimple.go
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package midsimple
import (
"net/http"
"sync"
)
// MidSimple simple middleware manager
type MidSimple struct {
list []func(http.Handler) http.Handler
sync.Mutex
}
// New creates an instance of MidSimple middleware manager and adds middlewares if any
func New(middleware ...func(http.Handler) http.Handler) *MidSimple {
ms := new(MidSimple)
if len(middleware) > 0 {
ms.Use(middleware...)
}
return ms
}
type handlerFuncWrapper struct {
hfunc http.HandlerFunc
}
// ServeHTTP runs wrapped handler function
func (wrapper *handlerFuncWrapper) ServeHTTP(w http.ResponseWriter, r *http.Request) {
wrapper.hfunc(w, r)
}
// Use adds middlewares to the queue
func (m *MidSimple) Use(middleware ...func(http.Handler) http.Handler) *MidSimple {
m.Lock()
defer m.Unlock()
m.list = append(m.list, middleware...)
return m
}
// Split creates copy of the chain to split the middleware flow
func (m *MidSimple) Split() *MidSimple {
n := make([]func(http.Handler) http.Handler, len(m.list))
copy(n, m.list)
return &MidSimple{list: n}
}
// Reset clears list of middlewares and allows use reuse it
func (m *MidSimple) Reset() *MidSimple {
m.Lock()
defer m.Unlock()
m.list = m.list[:0]
return m
}
// Wrap wraps the handler with middlewares from queue and returns wrapper version
func (m *MidSimple) Wrap(handler http.Handler) http.Handler {
m.Lock()
defer m.Unlock()
res := handler
for i := len(m.list) - 1; i >= 0; i-- {
res = m.list[i](res)
}
return res
}
// WrapFunc wraps HandlerFunc with middlewares from queue and returns wrapper version
func (m *MidSimple) WrapFunc(handlerFunc http.HandlerFunc) http.Handler {
handler := http.Handler(&handlerFuncWrapper{hfunc: handlerFunc})
return m.Wrap(handler)
}
// WrapRevert wraps the handler with middlewares from queue but in reverted sequence and returns wrapper version
func (m *MidSimple) WrapRevert(handler http.Handler) http.Handler {
m.Lock()
defer m.Unlock()
res := handler
for i := range m.list {
res = m.list[i](res)
}
return res
}
// WrapRevertFunc wraps the HandlerFunc with middlewares from queue but in reverted sequence and returns wrapper version
func (m *MidSimple) WrapRevertFunc(handlerFunc http.HandlerFunc) http.Handler {
handler := http.Handler(&handlerFuncWrapper{hfunc: handlerFunc})
return m.WrapRevert(handler)
}