2024-08-21 10:04:09 +02:00
|
|
|
package tools
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
"strings"
|
|
|
|
|
|
|
|
"github.com/nats-io/nats.go"
|
|
|
|
)
|
|
|
|
|
|
|
|
type NATSMethod int
|
|
|
|
|
|
|
|
const (
|
|
|
|
REMOVE NATSMethod = iota
|
|
|
|
CREATE
|
|
|
|
)
|
|
|
|
|
|
|
|
func NameToMethod(name string) NATSMethod {
|
|
|
|
for _, v := range [...]NATSMethod{REMOVE, CREATE} {
|
|
|
|
if strings.Contains(strings.ToLower(v.String()), strings.ToLower(name)) {
|
|
|
|
return v
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return -1
|
|
|
|
}
|
|
|
|
|
|
|
|
func (d NATSMethod) GenerateKey(name string) string {
|
|
|
|
return name + "_" + d.String()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (d NATSMethod) String() string {
|
2024-08-22 15:04:01 +02:00
|
|
|
return [...]string{"remove", "create", "discovery"}[d]
|
2024-08-21 10:04:09 +02:00
|
|
|
}
|
|
|
|
|
2024-08-21 10:21:17 +02:00
|
|
|
type natsCaller struct{}
|
2024-08-21 10:04:09 +02:00
|
|
|
|
2024-08-21 10:21:17 +02:00
|
|
|
func NewNATSCaller() *natsCaller {
|
|
|
|
return &natsCaller{}
|
2024-08-21 10:04:09 +02:00
|
|
|
}
|
|
|
|
|
2024-08-21 10:21:17 +02:00
|
|
|
func (o *natsCaller) SetNATSPub(dataName string, method NATSMethod, data interface{}) string {
|
|
|
|
if GetConfig().NATSUrl == "" {
|
2024-08-21 10:04:09 +02:00
|
|
|
return " -> NATS_SERVER is not set"
|
|
|
|
}
|
2024-08-21 10:21:17 +02:00
|
|
|
nc, err := nats.Connect(GetConfig().NATSUrl)
|
2024-08-21 10:04:09 +02:00
|
|
|
if err != nil {
|
|
|
|
return " -> Could not reach NATS server : " + err.Error()
|
|
|
|
}
|
|
|
|
defer nc.Close()
|
|
|
|
js, err := json.Marshal(data)
|
|
|
|
if err != nil {
|
|
|
|
return " -> " + err.Error()
|
|
|
|
}
|
|
|
|
err = nc.Publish(method.GenerateKey(dataName), js)
|
|
|
|
if err != nil {
|
|
|
|
return " -> " + err.Error()
|
|
|
|
}
|
|
|
|
return ""
|
|
|
|
}
|