-
Notifications
You must be signed in to change notification settings - Fork 0
/
connector.go
69 lines (52 loc) · 1.14 KB
/
connector.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
package syslog2nats
import (
"github.com/g41797/sputnik"
"github.com/nats-io/nats.go"
)
const connectorConfName = "connector"
type brokerConnConfig struct {
CONN_URL string
}
var _ sputnik.ServerConnector = &natsConnector{}
func NewConnector() sputnik.ServerConnector {
return new(natsConnector)
}
type NatsConnection struct {
Shared bool
NatsConn *nats.Conn
}
type natsConnector struct {
sc *NatsConnection
}
func (c *natsConnector) Connect(cf sputnik.ConfFactory) (conn sputnik.ServerConnection, err error) {
if c.IsConnected() {
return c.sc, nil
}
var conf brokerConnConfig
if err = cf(connectorConfName, &conf); err != nil {
return nil, err
}
nc, err := nats.Connect(conf.CONN_URL)
if err != nil {
return nil, err
}
c.sc = &NatsConnection{true, nc}
return c.sc, nil
}
func (c *natsConnector) IsConnected() bool {
if c.sc == nil {
return false
}
if c.sc.NatsConn.IsClosed() {
return false
}
return true
}
func (c *natsConnector) Disconnect() {
if c.sc.NatsConn != nil {
// Because connector block is closed last
// by sputnik, it's save to use Close() instead of Drain()
c.sc.NatsConn.Close()
}
c.sc = nil
}