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 { return [...]string{"remove", "create", "discovery"}[d] } type natsCaller struct{} func NewNATSCaller() *natsCaller { return &natsCaller{} } func (o *natsCaller) SetNATSPub(dataName string, method NATSMethod, data interface{}) string { if GetConfig().NATSUrl == "" { return " -> NATS_SERVER is not set" } nc, err := nats.Connect(GetConfig().NATSUrl) 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 "" }