-
Notifications
You must be signed in to change notification settings - Fork 0
/
subscriber.go
79 lines (69 loc) · 1.58 KB
/
subscriber.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
package pubsub
import (
"fmt"
"sync"
)
// Subscribers is a map of subscriber name to subscriber
type Subscribers map[string]*Subscriber
// Subscriber is a struct that holds the subscriber name, message channel and topics
type Subscriber struct {
Name string
Message chan *Message
Topics map[string]bool
Lock sync.RWMutex
Destroyed bool
}
// NewSubscriber creates a new subscriber
func NewSubscriber(name string) *Subscriber {
return &Subscriber{
Name: name,
Message: make(chan *Message),
Topics: map[string]bool{},
Lock: sync.RWMutex{},
}
}
// add topic to subscriber
func (s *Subscriber) AddTopic(topic string) {
s.Lock.Lock()
defer s.Lock.Unlock()
s.Topics[topic] = true
}
// remove topic from subscriber
func (s *Subscriber) RemoveTopic(topic string) {
s.Lock.Lock()
defer s.Lock.Unlock()
delete(s.Topics, topic)
}
// get topics from subscriber
func (s *Subscriber) GetTopics() []string {
s.Lock.RLock()
defer s.Lock.RUnlock()
topics := make([]string, 0, len(s.Topics))
for topic := range s.Topics {
topics = append(topics, topic)
}
return topics
}
// get message from subscriber
func (s *Subscriber) GetMessage() <-chan *Message {
return s.Message
}
// signal message to subscriber
func (s *Subscriber) Signal(msg *Message) *Subscriber {
fmt.Printf("Delivered message to %v : %v \n", s.Name, msg.Payload)
s.Lock.RLock()
if !s.Destroyed {
s.Message <- msg
}
s.Lock.RUnlock()
return s
}
// destroy subscriber
func (s *Subscriber) Destroy() {
s.Lock.Lock()
defer s.Lock.Unlock()
if !s.Destroyed {
close(s.Message)
s.Destroyed = true
}
}