-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathpubsub.go
63 lines (51 loc) · 1 KB
/
pubsub.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 main
import "sync"
var (
topicsmu sync.Mutex
topics = map[string][]Subscriber{}
)
type Subscriber interface {
Send([]byte)
}
// pub sends data to all subscribers of a given topic
func pub(topic string, data []byte) {
topicsmu.Lock()
defer topicsmu.Unlock()
if topic, ok := topics[topic]; ok {
for _, sub := range topic {
sub.Send(data)
}
}
if topic, ok := topics[""]; ok {
for _, sub := range topic {
sub.Send(data)
}
}
}
// sub registers a new Subscriber for a topic
func sub(topic string, sub Subscriber) {
topicsmu.Lock()
defer topicsmu.Unlock()
subs, _ := topics[topic]
topics[topic] = append(subs, sub)
}
// unsub removes a new Subscriber from a topic
func unsub(topic string, sub Subscriber) {
topicsmu.Lock()
defer topicsmu.Unlock()
subs, ok := topics[topic]
if !ok {
return
}
for i, tsub := range subs {
if tsub == sub {
subs = append(subs[:i], subs[i+1:]...)
break
}
}
if len(subs) == 0 {
delete(topics, topic)
} else {
topics[topic] = subs
}
}