NATS is an OCLIB tool
This commit is contained in:
44
tools/conf.go
Normal file
44
tools/conf.go
Normal file
@@ -0,0 +1,44 @@
|
||||
package tools
|
||||
|
||||
import "sync"
|
||||
|
||||
// ===================================================
|
||||
// This class has to be updated everytime
|
||||
// a new configuration variable is defined
|
||||
// in a componant that imports oc-lib
|
||||
// ===================================================
|
||||
|
||||
type Config struct {
|
||||
NATSUrl string
|
||||
MongoUrl string
|
||||
MongoDatabase string
|
||||
}
|
||||
|
||||
func (c Config) GetUrl() string {
|
||||
return c.MongoUrl
|
||||
}
|
||||
|
||||
func (c Config) GetDatabase() string {
|
||||
return c.MongoDatabase
|
||||
}
|
||||
|
||||
var instance *Config
|
||||
var once sync.Once
|
||||
|
||||
func GetConfig() *Config {
|
||||
once.Do(func() {
|
||||
instance = &Config{}
|
||||
})
|
||||
return instance
|
||||
}
|
||||
|
||||
func SetConfig(url string, database string, natsUrl string) *Config {
|
||||
once.Do(func() {
|
||||
instance = &Config{
|
||||
MongoUrl: url,
|
||||
MongoDatabase: database,
|
||||
NATSUrl: natsUrl,
|
||||
}
|
||||
})
|
||||
return instance
|
||||
}
|
||||
62
tools/nats_caller.go
Normal file
62
tools/nats_caller.go
Normal file
@@ -0,0 +1,62 @@
|
||||
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"}[d]
|
||||
}
|
||||
|
||||
type NATSCaller struct {
|
||||
natsUrl string
|
||||
}
|
||||
|
||||
func NewNATSCaller(url string) *NATSCaller {
|
||||
return &NATSCaller{
|
||||
natsUrl: url,
|
||||
}
|
||||
}
|
||||
|
||||
func (o *NATSCaller) SetNATSPub(dataName string, method NATSMethod, data interface{}) string {
|
||||
if o.natsUrl == "" {
|
||||
return " -> NATS_SERVER is not set"
|
||||
}
|
||||
nc, err := nats.Connect(o.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 ""
|
||||
}
|
||||
Reference in New Issue
Block a user