-
-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathpubsub.go
78 lines (65 loc) · 1.36 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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package main
import (
"sync"
)
type Subscription struct {
channel string
subscribers []chan<- string
}
type PubSub struct {
subscriptions map[string]*Subscription
mu sync.RWMutex
}
func NewPubSub() *PubSub {
return &PubSub{
subscriptions: make(map[string]*Subscription),
}
}
func (ps *PubSub) Subscribe(channel string) chan string {
ps.mu.Lock()
defer ps.mu.Unlock()
sub, exists := ps.subscriptions[channel]
if !exists {
sub = &Subscription{
channel: channel,
subscribers: make([]chan<- string, 0),
}
ps.subscriptions[channel] = sub
}
ch := make(chan string, 1)
sub.subscribers = append(sub.subscribers, ch)
return ch
}
func (ps *PubSub) Unsubscribe(channel string, subscriber chan string) {
ps.mu.Lock()
defer ps.mu.Unlock()
sub, exists := ps.subscriptions[channel]
if exists {
for i, ch := range sub.subscribers {
if ch == subscriber {
sub.subscribers = append(sub.subscribers[:i], sub.subscribers[i+1:]...)
break
}
}
}
}
func (ps *PubSub) UnsubscribeAll() {
ps.subscriptions = make(map[string]*Subscription)
}
func (ps *PubSub) Publish(channel, message string) int {
ps.mu.RLock()
defer ps.mu.RUnlock()
sub, exists := ps.subscriptions[channel]
if exists {
count := 0
for _, ch := range sub.subscribers {
select {
case ch <- message:
count++
default:
}
}
return count
}
return 0
}