package notify import ( "encoding/json" "fmt" "time" "github.com/nats-io/nats.go" "github.com/nats-io/nkeys" ) const DEFAULT_SUBJECT = "home2rjusnet.notifications" type BusNotification struct { ID uint32 `json:"id,omitempty"` Summary string `json:"summary"` Body string `json:"body,omitempty"` Timeout time.Duration `json:"timeout,omitempty"` } type NotificationService struct { Subject string nc *nats.Conn } func NewNotificationService(url, nkey string) (*NotificationService, error) { kp, err := nkeys.FromSeed([]byte(nkey)) if err != nil { return nil, fmt.Errorf("error creating nkey: %v", err) } pub, err := kp.PublicKey() if err != nil { return nil, fmt.Errorf("error getting public key: %v", err) } opt := nats.Nkey(pub, kp.Sign) nc, err := nats.Connect(url, opt) if err != nil { return nil, fmt.Errorf("error connecting to nats: %v", err) } return &NotificationService{nc: nc, Subject: DEFAULT_SUBJECT}, nil } func (n *NotificationService) Notify(msg *BusNotification) error { data, err := json.Marshal(msg) if err != nil { return fmt.Errorf("error marshalling notification: %v", err) } err = n.nc.Publish(n.Subject, data) if err != nil { return fmt.Errorf("error publishing notification: %v", err) } return nil } func (n *NotificationService) Close() { n.nc.Close() }