forked from ShiningRush/droplet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pipe.go
86 lines (69 loc) · 1.49 KB
/
pipe.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
package droplet
type Orchestrator func(mws []Middleware) []Middleware
type Handler func(ctx Context) (interface{}, error)
type BasePipe struct {
mwOrchestrator Orchestrator
mws []Middleware
}
func NewPipe() *BasePipe {
return &BasePipe{}
}
func (p *BasePipe) SetOrchestrator(o Orchestrator) *BasePipe {
p.mwOrchestrator = o
return p
}
func (p *BasePipe) Add(mw Middleware) *BasePipe {
p.mws = append(p.mws, mw)
return p
}
func (p *BasePipe) AddIf(mw Middleware, predicate bool) *BasePipe {
if predicate {
p.Add(mw)
}
return p
}
func (p *BasePipe) AddRange(mws []Middleware) *BasePipe {
for _, mw := range mws {
p.Add(mw)
}
return p
}
type RunOpt struct {
InitContext Context
}
type SetRunOpt func(opt *RunOpt)
func InitContext(ctx Context) SetRunOpt {
return func(opt *RunOpt) {
opt.InitContext = ctx
}
}
func (p *BasePipe) Run(handler Handler, opts ...SetRunOpt) (interface{}, error) {
opt := &RunOpt{}
for i := range opts {
opts[i](opt)
}
initCtx := opt.InitContext
if initCtx == nil {
initCtx = NewContext()
}
handlerMw := NewHandlerMiddleware(handler)
if Option.Orchestrator != nil {
p.mws = Option.Orchestrator(p.mws)
}
if p.mwOrchestrator != nil {
p.mws = p.mwOrchestrator(p.mws)
}
for i, mw := range p.mws {
if i < len(p.mws)-1 {
mw.SetNext(p.mws[i+1])
continue
}
mw.SetNext(handlerMw)
}
if len(p.mws) == 0 {
err := handlerMw.Handle(initCtx)
return initCtx, err
}
err := p.mws[0].Handle(initCtx)
return initCtx.Output(), err
}