-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpublisher.go
74 lines (62 loc) · 1.33 KB
/
publisher.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
package mediator
import (
"context"
"fmt"
)
type Event interface{}
type EventHandler func(ctx context.Context, event Event) error
type Publisher interface {
Publish(ctx context.Context, event Event) error
PublishAsync(ctx context.Context, event Event) Async
}
type publisher struct {
register Register
}
func newPublisher(register Register) Publisher {
if register == nil {
panic(fmt.Errorf("register value cannot be nil"))
}
return &publisher{
register: register,
}
}
func (p *publisher) Publish(ctx context.Context, event Event) error {
if fns, ok := p.register.GetEventHandler(event); ok {
for _, fn := range fns {
if err := fn(ctx, event); err != nil {
return err
}
}
return nil
}
return fmt.Errorf("event handler not found")
}
func (p *publisher) PublishAsync(ctx context.Context, event Event) Async {
var (
err error
selector = make(chan struct{})
)
go func() {
defer close(selector)
if fns, ok := p.register.GetEventHandler(event); ok {
for _, fn := range fns {
if err = fn(ctx, event); err != nil {
break
}
}
} else {
err = fmt.Errorf("event handler not found")
}
}()
return &async{
ctx: ctx,
await: func(ctx context.Context) (interface{}, error) {
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-selector:
return nil, err
}
},
}
}