forked from vindalu/go-vindalu-client
/
subscriber.go
94 lines (77 loc) · 2.2 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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package vindalu
import (
"net/http"
"io/ioutil"
"encoding/json"
"fmt"
log "github.com/euforia/simplelog"
"github.com/nats-io/nats"
"github.com/vindalu/vindalu/core"
)
type VindaluSubscriber struct {
conn *nats.Conn
enConn *nats.EncodedConn
}
func NewVindaluSubscriber(server string, logger *log.Logger) (vs *VindaluSubscriber, err error) {
vs = &VindaluSubscriber{}
opts := nats.DefaultOptions
opts.Servers, err = GetNatsServers(server)
if err != nil {
return
}
if vs.conn, err = opts.Connect(); err != nil {
return
}
logger.Debug.Printf("nats client connected to: %v!\n", vs.conn.ConnectedUrl())
vs.conn.Opts.ReconnectedCB = func(nc *nats.Conn) {
logger.Debug.Printf("nats client reconnected to: %v!\n", nc.ConnectedUrl())
}
vs.conn.Opts.DisconnectedCB = func(_ *nats.Conn) {
logger.Debug.Printf("nats client disconnected!\n")
}
vs.enConn, err = nats.NewEncodedConn(vs.conn, nats.JSON_ENCODER)
return
}
func GetNatsServers(server string) (natsServers []string, err error) {
var (
clusterStatus *core.VindaluClusterStatus
resp *http.Response
body []byte
)
resp, err = http.Get(server + "/status")
if err != nil {
return
}
defer resp.Body.Close()
body, err = ioutil.ReadAll(resp.Body)
err = json.Unmarshal(body, &clusterStatus)
if err != nil {
return
}
for _, member := range clusterStatus.ClusterMemberAddrs() {
natsServers = append(natsServers, fmt.Sprintf("nats://%s:%d", member, 4223))
}
return
}
func (vs *VindaluSubscriber) Subscribe(topic string) (ch chan *core.Event, err error) {
// Goes no where as we do not want to allow writing (i.e publishing)
//if err = vs.enConn.BindSendChan(topic, make(chan *core.Event)); err != nil {
// return
//}
ch = make(chan *core.Event)
_, err = vs.enConn.BindRecvChan(topic, ch)
return
}
func (vs *VindaluSubscriber) SubscribeQueueGroup(topic, qGroup string) (ch chan *core.Event, err error) {
// Goes no where as we do not want to allow writing (i.e publishing)
//if err = vs.enConn.BindSendChan(topic, make(chan *core.Event)); err != nil {
// return
//}
ch = make(chan *core.Event)
_, err = vs.enConn.BindRecvQueueChan(topic, qGroup, ch)
return
}
func (vs *VindaluSubscriber) Close() {
vs.enConn.Close()
vs.conn.Close()
}