-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathhandler.go
77 lines (54 loc) · 1.34 KB
/
handler.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
package flow
import (
"github.com/gogap/config"
"github.com/gogap/context"
)
type SubscriberFunc func(context.Context)
type HandlerFunc func(context.Context, config.Configuration) error
func (p HandlerFunc) Run(ctx context.Context, conf config.Configuration) error {
return p(ctx, conf)
}
func (p HandlerFunc) Then(next HandlerFunc, conf config.Configuration) HandlerFunc {
nextConfig := conf
var h HandlerFunc = func(ctx context.Context, conf config.Configuration) (err error) {
err = p.Run(ctx, conf)
if err != nil {
return
}
err = next.Run(ctx, nextConfig)
if err != nil {
return
}
return
}
return h
}
func (p HandlerFunc) Subscribe(subscribers ...SubscriberFunc) HandlerFunc {
var h HandlerFunc = func(ctx context.Context, conf config.Configuration) (err error) {
err = p.Run(ctx, conf)
if len(subscribers) > 0 {
var newCtx context.Context
if ctx == nil {
newCtx = context.NewContext()
} else {
newCtx = ctx.Copy()
}
if err != nil {
newCtx.WithError(err)
}
p.publish(newCtx, subscribers...)
}
return
}
return h
}
func (p HandlerFunc) publish(ctx context.Context, subscribers ...SubscriberFunc) {
if len(subscribers) == 0 {
return
}
go func(ctx context.Context, subscribers ...SubscriberFunc) {
for _, s := range subscribers {
s(ctx)
}
}(ctx, subscribers...)
}