/
eventbus.go
87 lines (71 loc) · 1.32 KB
/
eventbus.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
87
package event
import (
"strings"
"sync"
)
type EventBus struct {
mux sync.RWMutex
subscribers []*Subscriber
}
func NewEventBus() *EventBus {
return &EventBus{
subscribers: make([]*Subscriber, 0),
}
}
func (e *EventBus) Publish(topic string, msg any) int {
e.mux.RLock()
defer e.mux.RUnlock()
if topic == "" {
return 0
}
count := 0
for _, s := range e.subscribers {
if s.Has(topic) {
s.out <- msg
count++
}
}
return count
}
func (e *EventBus) Subscribe(topic string) *Subscriber {
e.mux.Lock()
defer e.mux.Unlock()
s := NewSubscriber(topic)
e.subscribers = append(e.subscribers, s)
return s
}
func (e *EventBus) Unsubscribe(s *Subscriber) {
e.mux.Lock()
defer e.mux.Unlock()
close(s.out)
for i := range e.subscribers {
if e.subscribers[i] == s {
e.subscribers = append(e.subscribers[:i], e.subscribers[i+1:]...)
break
}
}
}
type Subscriber struct {
all bool
topic string
out chan any
}
func NewSubscriber(topic string) *Subscriber {
all := false
if len(topic) == 0 || strings.EqualFold(topic, "*") {
all = true
}
return &Subscriber{
all: all,
topic: topic,
out: make(chan any, 1e3)}
}
func (s *Subscriber) Out() <-chan any {
return s.out
}
func (s *Subscriber) Has(topic string) bool {
if s.all {
return true
}
return strings.EqualFold(s.topic, topic)
}