/
subscriptions.go
62 lines (53 loc) · 1.34 KB
/
subscriptions.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
package redisroutes
import (
"github.com/garyburd/redigo/redis"
"github.com/soveran/redisurl"
)
// Subscription Handling
type SubscriptionHandler struct {
index map[string]subscription
addr string
}
// Maps a url to redis Subscribe channel
type subscription struct {
psc *redis.PubSubConn
eventStream string
msgStream *chan string
}
func (sh *SubscriptionHandler) CreateSub(eventStream string, msgStream *chan string) {
conn, err := redisurl.ConnectToURL(sh.addr)
if err != nil {
panic(err)
}
psc := redis.PubSubConn{Conn: conn}
err = psc.Subscribe(eventStream)
if err != nil {
panic(err)
}
sh.index[eventStream] = subscription{&psc, eventStream, msgStream}
}
// Register an array of subscriptions
func (sh *SubscriptionHandler) CreateSubs(eventStreams []string, msgStream *chan string) {
for _, eventStream := range eventStreams {
sh.CreateSub(eventStream, msgStream)
}
}
// Begin listening on all subscriptions
// Each subscription will concurrently handle events and output to
// their associated msgStream
func (sh *SubscriptionHandler) Listen() {
for _, sub := range sh.index {
go sub.listen()
}
}
// listen for published events and send to message channel
func (s subscription) listen() {
for {
switch v := s.psc.Receive().(type) {
case redis.Message:
*s.msgStream <- string(v.Data)
case error:
return
}
}
}