-
Notifications
You must be signed in to change notification settings - Fork 2
/
nats.go
87 lines (73 loc) · 2.16 KB
/
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
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
package nhook
import (
"crypto/tls"
"crypto/x509"
"fmt"
"io/ioutil"
"strings"
"github.com/nats-io/go-nats"
"github.com/sirupsen/logrus"
)
// NatsConfig represents the minimum entries that are needed to connect to Nats over TLS
type NatsConfig struct {
CAFiles []string `json:"ca_files"`
KeyFile string `json:"key_file"`
CertFile string `json:"cert_file"`
Servers []string `json:"servers"`
}
// ServerString will build the proper string for nats connect
func (config *NatsConfig) ServerString() string {
return strings.Join(config.Servers, ",")
}
// LogFields will return all the fields relevant to this config
func (config *NatsConfig) LogFields() logrus.Fields {
return logrus.Fields{
"servers": config.Servers,
"ca_files": config.CAFiles,
"key_file": config.KeyFile,
"cert_file": config.CertFile,
}
}
// TLSConfig will load the TLS certificate
func (config *NatsConfig) TLSConfig() (*tls.Config, error) {
pool := x509.NewCertPool()
for _, caFile := range config.CAFiles {
caData, err := ioutil.ReadFile(caFile)
if err != nil {
return nil, err
}
if !pool.AppendCertsFromPEM(caData) {
return nil, fmt.Errorf("Failed to add CA cert at %s", caFile)
}
}
cert, err := tls.LoadX509KeyPair(config.CertFile, config.KeyFile)
if err != nil {
return nil, err
}
tlsConfig := &tls.Config{
RootCAs: pool,
Certificates: []tls.Certificate{cert},
MinVersion: tls.VersionTLS12,
}
return tlsConfig, nil
}
// ConnectToNats will do a TLS connection to the nats servers specified
func ConnectToNats(config *NatsConfig) (*nats.Conn, error) {
tlsConfig, err := config.TLSConfig()
if err != nil {
return nil, err
}
return nats.Connect(config.ServerString(), nats.Secure(tlsConfig))
}
// ConnectToNatsWithError will do a TLS connection to the nats servers specified
func ConnectToNatsWithError(config *NatsConfig, eHandler nats.ErrHandler) (*nats.Conn, error) {
tlsConfig, err := config.TLSConfig()
if err != nil {
return nil, err
}
if eHandler != nil {
return nats.Connect(config.ServerString(), nats.Secure(tlsConfig), nats.ErrorHandler(eHandler))
} else {
return nats.Connect(config.ServerString(), nats.Secure(tlsConfig))
}
}