hpds_mq/config/config.go

88 lines
2.3 KiB
Go
Raw Normal View History

2022-10-23 14:03:36 +08:00
package config
import (
"bytes"
"fmt"
"github.com/spf13/viper"
"os"
consulapi "github.com/hashicorp/consul/api"
_ "github.com/spf13/viper/remote"
"gopkg.in/yaml.v3"
)
type MessageQueueConfig struct {
Name string `yaml:"name,omitempty"`
Host string `yaml:"host,omitempty"`
Port int `yaml:"port,omitempty"`
Mode string `yaml:"mode,omitempty"`
Token string `yaml:"token,omitempty"`
CascadeNode []MessageQueueConfig `yaml:"cascadeNode,omitempty"`
Consul ConsulConfig `yaml:"consul,omitempty"`
}
type ConsulConfig struct {
Host string `yaml:"host,omitempty"`
Port int `yaml:"port,omitempty"`
Interval int `yaml:"interval,omitempty"`
Timeout int `yaml:"timeout,omitempty"`
Deregister int `yaml:"deregister,omitempty"`
Tags []string `yaml:"tags,omitempty"`
}
func ParseConfigByFile(path string) (cfg *MessageQueueConfig, err error) {
buffer, err := os.ReadFile(path)
if err != nil {
return nil, err
}
return load(buffer)
}
func load(buf []byte) (cfg *MessageQueueConfig, err error) {
cViper := viper.New()
cViper.SetConfigType("yaml")
cfg = new(MessageQueueConfig)
cViper.ReadConfig(bytes.NewBuffer(buf))
err = cViper.Unmarshal(cfg)
if err != nil {
return nil, err
}
return
}
func UpdateLocalConfig(cfg *MessageQueueConfig, fn string) error {
data, err := yaml.Marshal(cfg)
if err != nil {
return err
}
err = os.WriteFile(fn, data, 0600)
return err
}
func UpdateRemoteConfig(cfg *MessageQueueConfig) error {
consulClient, err := consulapi.NewClient(&consulapi.Config{Address: fmt.Sprintf("%s:%d", cfg.Consul.Host, cfg.Consul.Port)})
if err != nil {
return err
}
val, err := yaml.Marshal(cfg)
if err != nil {
return err
}
p := &consulapi.KVPair{Key: fmt.Sprintf("hpds-pavement/hpds_mq/%s/%s", cfg.Mode, cfg.Name), Value: val}
if _, err = consulClient.KV().Put(p, nil); err != nil {
return err
}
return nil
}
func GetRemoteConfig(remoteAddr, path string) (cfg *MessageQueueConfig, err error) {
consulClient, err := consulapi.NewClient(&consulapi.Config{Address: remoteAddr})
if err != nil {
return nil, err
}
kv, _, err := consulClient.KV().Get(path, nil)
if err != nil {
return nil, err
}
return load(kv.Value)
}