-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnats.go
56 lines (45 loc) · 934 Bytes
/
nats.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
package main
import (
"fmt"
"github.com/nats-io/nats.go"
stan "github.com/nats-io/stan.go"
)
const (
ClusterID = "test-cluster"
)
type NATSClient struct {
ClusterID string
ClientID string
NATSHost string
}
func (c *NATSClient) IsConnected() bool {
nc, err := nats.Connect(c.NATSHost)
if err != nil {
fmt.Println(err)
return false
}
return nc.IsConnected()
}
func (c *NATSClient) Publish(payload []byte, channel string) error {
nc, err := nats.Connect(c.NATSHost)
if err != nil {
return err
}
sc, err := stan.Connect(c.ClusterID, c.ClientID, stan.NatsConn(nc))
if err != nil {
return err
}
defer sc.Close()
if err := sc.Publish(channel, payload); err != nil {
// TODO: return retriable/non-retriable error
return err
}
return nil
}
func NewNATSClient(host string) *NATSClient {
return &NATSClient{
NATSHost: host,
ClientID: "random", // TODO: randomize
ClusterID: ClusterID,
}
}