-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.go
75 lines (65 loc) · 1.59 KB
/
middleware.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
package ruffe
type Middleware struct {
h Handler
OnError func(Context, error) error
}
func NewMiddleware(h Handler) *Middleware {
return &Middleware{
h: h,
}
}
func NewMiddlewareFunc(f func(Context) error) *Middleware {
return NewMiddleware(HandlerFunc(f))
}
// Before create middleware which call Middleware handler before handler from argument
func (m *Middleware) Before(h Handler) *Middleware {
return &Middleware{
h: m.mwf(m.h, h),
}
}
// BeforeFunc do same as Before
func (m *Middleware) BeforeFunc(f func(Context) error) *Middleware {
return m.Before(HandlerFunc(f))
}
// After create middleware which call Middleware handler after handler from argument
func (m *Middleware) After(h Handler) *Middleware {
return &Middleware{
h: m.mwf(h, m.h),
}
}
// AfterFunc do same as After
func (m *Middleware) AfterFunc(f func(Context) error) *Middleware {
return m.After(HandlerFunc(f))
}
// Wrap crate middleware from f argument where pass Middleware handler as next argument
func (m *Middleware) Wrap(f func(ctx Context, next Handler) error) *Middleware {
return &Middleware{
h: HandlerFunc(func(ctx Context) error {
if ctx.done() {
return nil
}
return f(ctx, m.h)
}),
}
}
func (m *Middleware) mwf(first, last Handler) Handler {
return HandlerFunc(func(ctx Context) error {
if err := first.Handle(ctx); err != nil {
return err
}
if ctx.done() {
return nil
}
return last.Handle(ctx)
})
}
func (m *Middleware) Handle(ctx Context) error {
err := m.h.Handle(ctx)
if err == nil {
return nil
}
if m.OnError == nil {
return err
}
return m.OnError(ctx, err)
}