-
Notifications
You must be signed in to change notification settings - Fork 0
/
sender.go
71 lines (61 loc) 路 1.51 KB
/
sender.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
package mediator
import (
"context"
"fmt"
)
type Command interface{}
type CommandHandler func(ctx context.Context, command Command) (interface{}, error)
type Sender interface {
Send(ctx context.Context, command Command) (interface{}, error)
SendAsync(ctx context.Context, command Command) Async
}
type sender struct {
register Register
behavior Behavior
}
func newSender(register Register, behavior Behavior) Sender {
if register == nil {
panic(fmt.Errorf("register value cannot be nil"))
}
if behavior == nil {
panic(fmt.Errorf("behavior value cannot be nil"))
}
return &sender{
register: register,
behavior: behavior,
}
}
func (s *sender) Send(ctx context.Context, command Command) (result interface{}, err error) {
if fn, ok := s.register.GetCommandHandler(command); ok {
result, err = s.behavior.use(ctx, command, fn, 0)
} else {
err = fmt.Errorf("not found handler registered by %v", command)
}
return
}
func (s *sender) SendAsync(ctx context.Context, command Command) Async {
var (
selector = make(chan struct{})
err error
result interface{}
)
go func() {
defer close(selector)
if fn, ok := s.register.GetCommandHandler(command); ok {
result, err = s.behavior.use(ctx, command, fn, 0)
} else {
err = fmt.Errorf("not found handler registered by %v", command)
}
}()
return &async{
ctx: ctx,
await: func(ctx context.Context) (interface{}, error) {
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-selector:
return result, err
}
},
}
}