-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpubsub.go
66 lines (57 loc) · 1.54 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
package main
import (
"fmt"
"sync"
)
// PubSub represents the publish-subscribe system
type PubSub struct {
mu sync.RWMutex
subscribers map[string][]chan Value // Map of channels to their subscribers
}
// NewPubSub creates a new PubSub instance
func NewPubSub() *PubSub {
return &PubSub{
subscribers: make(map[string][]chan Value),
}
}
// Subscribe adds a client to a channel's list of subscribers
func (ps *PubSub) Subscribe(channel string) <-chan Value {
ps.mu.Lock()
defer ps.mu.Unlock()
ch := make(chan Value, 10) // Buffered channel for messages
ps.subscribers[channel] = append(ps.subscribers[channel], ch)
return ch
}
// Unsubscribe removes a client from a channel's list of subscribers
func (ps *PubSub) Unsubscribe(channel string, sub <-chan Value) {
ps.mu.Lock()
defer ps.mu.Unlock()
if subs, ok := ps.subscribers[channel]; ok {
for i, ch := range subs {
if ch == sub {
ps.subscribers[channel] = append(subs[:i], subs[i+1:]...)
close(ch)
break
}
}
// If no subscribers remain, delete the channel entry
if len(ps.subscribers[channel]) == 0 {
delete(ps.subscribers, channel)
}
}
}
// Publish sends a message to all subscribers of a channel
func (ps *PubSub) Publish(channel string, message Value) {
ps.mu.RLock()
defer ps.mu.RUnlock()
if subs, ok := ps.subscribers[channel]; ok {
for _, ch := range subs {
// Non-blocking send to prevent slow clients from halting the publisher
select {
case ch <- message:
default:
fmt.Println("Dropping message for slow subscriber")
}
}
}
}