🔥🔥 🌈 Golang configuration,use to Viper reading from remote Nacos config systems. Viper remote for Naocs.

Viper remote for Nacos

Golang configuration,use to Viper reading from remote Nacos config systems. Viper remote for Naocs.

runtime_viper := viper.New()

remote.SetOptions(&remote.Option{
   Url:         "localhost",
   Port:        80,
   NamespaceId: "public",
   GroupName:   "DEFAULT_GROUP",
   Config: 	remote.Config{ DataId: "config_dev" },
   Auth:        nil,
})

err := remote_viper.AddRemoteProvider("nacos", "localhost", "")
remote_viper.SetConfigType("yaml")

_ = remote_viper.ReadRemoteConfig()             //sync get remote configs to remote_viper instance memory . for example , remote_viper.GetString(key)
_ = remote_viper.WatchRemoteConfigOnChannel()   //async watch , auto refresh configs.

appName := remote_viper.GetString("key")   // sync get config by key

fmt.Println(appName)
Owner
yoyofxteam
YoyoGo and Other Framework
yoyofxteam
Similar Resources

Simple Config Format for Golang.

IndentText Simple Configuration Format that tries to be easy to use and understand at a glance. Unlike other formats, IndentText does not have any typ

Nov 26, 2021

Golang config.yaml loader

Description goconfig is a configuration library designed using the following pri

May 31, 2022

Simple, useful and opinionated config loader.

aconfig Simple, useful and opinionated config loader. Rationale There are many solutions regarding configuration loading in Go. I was looking for a si

Dec 26, 2022

A lightweight yet powerful config package for Go projects

Config GoLobby Config is a lightweight yet powerful config package for Go projects. It takes advantage of env files and OS variables alongside config

Dec 11, 2022

Composable, observable and performant config handling for Go for the distributed processing era

Konfig Composable, observable and performant config handling for Go. Written for larger distributed systems where you may have plenty of configuration

Dec 11, 2022

create a bootable disk image from Docker image or a yaml config

docker2boot docker2boot creates a bootable disk from either a Docker image or a config yaml file Features status dns Y cloud-init Y network Y ssh TODO

Oct 30, 2022

Sidecar to watch a config folder and reload a process when it changes

A small (3MB uncompressed docker image), efficient (via inotify) sidecar to trigger application reloads when configuration changes.

Dec 29, 2022

Little Go tool to infer an uncrustify config file from an expected format

uncrustify-infer Little Go tool to infer an uncrustify config file from an expected format Install This tool relies on an uncrustify executable, you m

Oct 8, 2021
Comments
  • 连接 阿里云 MSE Nacos 取配置失败,也不报任何错误,取回的内容为空

    连接 阿里云 MSE Nacos 取配置失败,也不报任何错误,取回的内容为空

    连接 阿里云 MSE Nacos 取配置失败,也不报任何错误,取回的内容为空

    	remote.SetOptions(&remote.Option{
    		Url:         Config.Mse.Server,
    		Port:        uint64(Config.Mse.Port),
    		NamespaceId: Config.Mse.Namespace,
    		GroupName:   Config.Mse.GroupName,
    		Config:      remote.Config{DataId: Config.Mse.ConfigName},
    		Auth:        nil,
    	})
    	remoteConfig := viper.New()
    	err := remoteConfig.AddRemoteProvider("nacos", "mse-8f7b0b60-nacos-ans.mse.aliyuncs.com", "")
    	if err != nil {
    		fmt.Println("加载远程配置失败 :", err.Error())
    	}
    	remoteConfig.SetConfigType("yaml")
    	err = remoteConfig.ReadRemoteConfig()
    	if err != nil {
    		fmt.Println("加载远程配置失败 :", err.Error())
    	}
    	fmt.Println("加载远程配置: Config = ", remoteConfig.GetString("log.level"))
    
    	loadFromViper(remoteConfig)
    
    	fmt.Println("加载远程配置: Config = ", ObjToJSON(Config))
    
  • 连接自己部署的服务器也是失败

    连接自己部署的服务器也是失败

    import ( "github.com/sirupsen/logrus" "github.com/spf13/viper" _ "github.com/spf13/viper/remote" remote "github.com/yoyofxteam/nacos-viper-remote" )

    func SetRemoteYaml() {

    var remoteViper = viper.New()
    remote.SetOptions(&remote.Option{
    	Url:          	"192.168.123.22",
    	Port:        	31150,
    	NamespaceId: 	"xincan-dev-0001",
    	GroupName:   	"dev_group",
    	Config: 		remote.Config{
    		DataId: "test-gokit-dev.yaml",
    	},
    	Auth: nil,
    })
    
    remoteErr := remoteViper.AddRemoteProvider("nacos", "192.168.123.22", "")
    remoteViper.SetConfigType("yaml")
    _ = remoteViper.ReadRemoteConfig()
    _ = remoteViper.WatchRemoteConfigOnChannel()
    if remoteErr == nil {
    	logrus.WithField("fail", remoteErr).Error("viper获取Nacos配置中心数据失败")
    }
    

    }

  • 其实没必要这么设计

    其实没必要这么设计

    直接在ListenConfig的回调里面新建一个Vipper对象,然后Store到一个线程安全的对象里,用的时候每次Load一次即可…

    type SafeVipper struct {
    	lock   sync.RWMutex
    	vipper *viper.Viper
    }
    
    func (sv *SafeVipper) Load() *viper.Viper {
    	sv.lock.RLock()
    	defer sv.lock.RUnlock()
    	return sv.vipper
    }
    
    func (sv *SafeVipper) Store(vp *viper.Viper) {
    	sv.lock.Lock()
    	sv.vipper = vp
    	sv.lock.Unlock()
    }
    
    func GetViper(group, dataId string, cbs ...func(*viper.Viper)) (*SafeVipper, chan struct{}) {
    	suffix := "yaml"
    	idx := strings.LastIndex(dataId, ".")
    	if idx >= 0 {
    		suffix = dataId[idx+1:]
    	}
    	sv := &SafeVipper{}
    	fn := func(namespace, group, dataId, data string) {
    		vp := viper.New()
    		vp.SetConfigType(suffix)
    		if err := vp.ReadConfig(bytes.NewReader([]byte(data))); err != nil {
    			log.Error("fail parse config file, group: %s, dataId: %s", group, dataId)
    		} else {
    			for _, cb := range cbs {
    				cb(vp)
    			}
    			//仅当解析成功才替换掉
    			sv.Store(vp)
    		}
    	}
    	// 第一次读入文件
    	data, err := configClient.GetConfig(vo.ConfigParam{
    		DataId: dataId,
    		Group:  group,
    	})
    	if err != nil || data == "" {
    		log.Fatal("fail to read config from %s, data:%s, err:%v", dataId, data, err)
    	}
    	fn("", group, dataId, data)
    	if sv.Load() == nil {
    		log.Fatal("fail to parse config file:%s, err:%s", dataId, err)
    	}
    	// 监听文件变化
    	err = configClient.ListenConfig(vo.ConfigParam{
    		DataId:   dataId,
    		Group:    group,
    		OnChange: fn,
    	})
    	if err != nil {
    		log.Fatal("fail to comm with nacos:%s", err)
    	}
    	ch := make(chan struct{}, 1)
    	go func() {
    		<-ch
    		_ = configClient.CancelListenConfig(vo.ConfigParam{
    			DataId: dataId,
    			Group:  group,
    		})
    	}()
    	return sv, ch
    }
    
Viper wrapper with config inheritance and key generation

piper - Simple Wrapper For Viper Single Source of Truth Generated Key Structs, No Typo Config Inheritance Multiple Config Strategies Support Cache For

Sep 26, 2022
Light weight, extensible configuration management library for Go. Built in support for JSON, TOML, YAML, env, command line, file, S3 etc. Alternative to viper.
Light weight, extensible configuration management library for Go. Built in support for JSON, TOML, YAML, env, command line, file, S3 etc. Alternative to viper.

koanf (pronounced conf; a play on the Japanese Koan) is a library for reading configuration from different sources in different formats in Go applicat

Jan 8, 2023
Jacket of spf13/viper: Simplified go configuration for wire-jacket.

Viper-Jacket: viper config for Wire-Jacket Jacket of spf13/viper: config for wire-jacket. Simplified env-based go configuration package using viper. b

Nov 18, 2021
Golang library for reading properties from configuration files in JSON and YAML format or from environment variables.

go-config Golang library for reading properties from configuration files in JSON and YAML format or from environment variables. Usage Create config in

Aug 22, 2022
⚙️ Dead Simple Config Management, load and persist config without having to think about where and how.

Configo Dead Simple Config Management, load and persist config without having to think about where and how. Install go get github.com/UltiRequiem/conf

Apr 6, 2022
Go-config - Config parser for go that supports environment vars and multiple yaml files

go-multiconfig This package is able to parse yaml config files. It supports gett

Jun 23, 2022
Tinyini - Bare-bones Go library for reading INI-like configuration files

tinyini tinyini is a minimalistic library for parsing INI-like configuration files. example configuration file globalkey = globalvalue [section] key

Jan 10, 2022
go implementation of lightbend's HOCON configuration library https://github.com/lightbend/config

HOCON (Human-Optimized Config Object Notation) Configuration library for working with the Lightbend's HOCON format. HOCON is a human-friendly JSON sup

Dec 3, 2022
Jul 4, 2022
A lightweight config center written by golang.

A lightweight config center written by golang.

Jan 21, 2022