nacos-viper-remote/viper_remote.go

65 lines
1.4 KiB
Go
Raw Permalink Normal View History

2021-04-29 19:54:59 +08:00
package nacos_viper_remote
import (
"bytes"
"errors"
"github.com/spf13/viper"
"io"
)
2021-07-29 19:30:03 +08:00
//var nacosOptions = &Option{}
2021-04-29 19:54:59 +08:00
func SetOptions(option *Option) {
2021-07-29 19:30:03 +08:00
manager, _ := NewNacosConfigManager(option)
viper.SupportedRemoteProviders = []string{"nacos"}
viper.RemoteConfig = &remoteConfigProvider{ConfigManager: manager}
2021-04-29 19:54:59 +08:00
}
type remoteConfigProvider struct {
2021-07-29 19:30:03 +08:00
ConfigManager *nacosConfigManager
2021-04-29 19:54:59 +08:00
}
func (rc *remoteConfigProvider) Get(rp viper.RemoteProvider) (io.Reader, error) {
2021-07-29 19:30:03 +08:00
cmt, err := rc.getConfigManager(rp)
2021-04-29 19:54:59 +08:00
if err != nil {
return nil, err
}
var b []byte
switch cm := cmt.(type) {
case viperConfigManager:
b, err = cm.Get(rp.Path())
}
if err != nil {
return nil, err
}
return bytes.NewReader(b), nil
}
func (rc *remoteConfigProvider) Watch(rp viper.RemoteProvider) (io.Reader, error) {
return rc.Get(rp)
}
func (rc *remoteConfigProvider) WatchChannel(rp viper.RemoteProvider) (<-chan *viper.RemoteResponse, chan bool) {
2021-07-29 19:30:03 +08:00
cmt, err := rc.getConfigManager(rp)
2021-04-29 19:54:59 +08:00
if err != nil {
return nil, nil
}
switch cm := cmt.(type) {
case viperConfigManager:
quit := make(chan bool)
viperResponseCh := cm.Watch("dataId", quit)
return viperResponseCh, quit
}
return nil, nil
}
2021-07-29 19:30:03 +08:00
func (rc *remoteConfigProvider) getConfigManager(rp viper.RemoteProvider) (interface{}, error) {
2021-04-29 19:54:59 +08:00
if rp.Provider() == "nacos" {
2021-07-29 19:30:03 +08:00
return rc.ConfigManager, nil
2021-04-29 19:54:59 +08:00
} else {
return nil, errors.New("The Nacos configuration manager is not supported!")
}
}