-
Notifications
You must be signed in to change notification settings - Fork 0
/
mq.go
63 lines (50 loc) · 822 Bytes
/
mq.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
package ipmq
import (
"crypto/rand"
"fmt"
"sync"
)
type MQ interface {
Register(c Consumer) (CancelFunc, error)
Push(Msg) error
}
type Msg interface{}
type CancelFunc func() error
type Consumer func(m Msg) error
type mq struct {
mu sync.RWMutex
cm map[string]Consumer
}
func key() string {
b := make([]byte, 8)
rand.Read(b)
return fmt.Sprintf("%x", b)
}
func (q *mq) Register(c Consumer) (CancelFunc, error) {
q.mu.Lock()
defer q.mu.Unlock()
k := key()
q.cm[k] = c
cfn := func() error {
q.mu.Lock()
defer q.mu.Unlock()
delete(q.cm, k)
return nil
}
return cfn, nil
}
func (q *mq) Push(m Msg) error {
q.mu.RLock()
defer q.mu.RUnlock()
for _, c := range q.cm {
go func(c Consumer) {
c(m)
}(c)
}
return nil
}
func New() MQ {
return &mq{
cm: make(map[string]Consumer),
}
}