nats.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. package nhook
  2. import (
  3. "crypto/tls"
  4. "crypto/x509"
  5. "fmt"
  6. "io/ioutil"
  7. "strings"
  8. "github.com/nats-io/nats.go"
  9. "github.com/sirupsen/logrus"
  10. )
  11. // NatsConfig represents the minimum entries that are needed to connect to Nats over TLS
  12. type NatsConfig struct {
  13. CAFiles []string `json:"ca_files"`
  14. KeyFile string `json:"key_file"`
  15. CertFile string `json:"cert_file"`
  16. Servers []string `json:"servers"`
  17. }
  18. // ServerString will build the proper string for nats connect
  19. func (config *NatsConfig) ServerString() string {
  20. return strings.Join(config.Servers, ",")
  21. }
  22. // LogFields will return all the fields relevant to this config
  23. func (config *NatsConfig) LogFields() logrus.Fields {
  24. return logrus.Fields{
  25. "servers": config.Servers,
  26. "ca_files": config.CAFiles,
  27. "key_file": config.KeyFile,
  28. "cert_file": config.CertFile,
  29. }
  30. }
  31. // TLSConfig will load the TLS certificate
  32. func (config *NatsConfig) TLSConfig() (*tls.Config, error) {
  33. pool := x509.NewCertPool()
  34. for _, caFile := range config.CAFiles {
  35. caData, err := ioutil.ReadFile(caFile)
  36. if err != nil {
  37. return nil, err
  38. }
  39. if !pool.AppendCertsFromPEM(caData) {
  40. return nil, fmt.Errorf("Failed to add CA cert at %s", caFile)
  41. }
  42. }
  43. cert, err := tls.LoadX509KeyPair(config.CertFile, config.KeyFile)
  44. if err != nil {
  45. return nil, err
  46. }
  47. tlsConfig := &tls.Config{
  48. RootCAs: pool,
  49. Certificates: []tls.Certificate{cert},
  50. MinVersion: tls.VersionTLS12,
  51. }
  52. return tlsConfig, nil
  53. }
  54. func ConnectToNatsNoTls(config *NatsConfig) (*nats.Conn, error) {
  55. return nats.Connect(config.ServerString(), nats.MaxReconnects(-1))
  56. }
  57. // ConnectToNats will do a TLS connection to the nats servers specified
  58. func ConnectToNats(config *NatsConfig) (*nats.Conn, error) {
  59. tlsConfig, err := config.TLSConfig()
  60. if err != nil {
  61. return nil, err
  62. }
  63. return nats.Connect(config.ServerString(), nats.Secure(tlsConfig))
  64. }
  65. // ConnectToNatsWithError will do a TLS connection to the nats servers specified
  66. func ConnectToNatsWithError(config *NatsConfig, eHandler nats.ErrHandler) (*nats.Conn, error) {
  67. tlsConfig, err := config.TLSConfig()
  68. if err != nil {
  69. return nil, err
  70. }
  71. if eHandler != nil {
  72. return nats.Connect(config.ServerString(), nats.Secure(tlsConfig), nats.ErrorHandler(eHandler))
  73. } else {
  74. return nats.Connect(config.ServerString(), nats.Secure(tlsConfig))
  75. }
  76. }