Viper 配置設定黨

配置設定黨

What is Viper

  • setting defaults

  • reading from JSON, TOML, YAML, HCL, envfile and Java properties config files

  • live watching and re-reading of config files (optional)

  • reading from environment variables

  • reading from remote config systems (etcd or Consul), and watching changes

  • reading from command line flags

  • reading from buffer

  • setting explicit values

sample


func viperSetting(configPath string) error {
	viper.SetConfigType(defaultConfigType)
	viper.AddConfigPath(configPath)
	viper.SetConfigName(serviceFileName)

	if err := viper.ReadInConfig(); err != nil {
		return errors.Errorf("viper.ReadInConfig error(%v)", err)
	}
	fmt.Println("viper.ConfigFileUsed OK:", viper.ConfigFileUsed())

	viper.AutomaticEnv() //export  SERVICE_NAME=test2
	viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
	
	err := viper.Unmarshal(&configData) //bind struct
	if err != nil {
		return errors.Errorf("viper.Unmarshal:(%v)", err)
	}

	fmt.Println("data:", viper.Get("service.name"))
	fmt.Println("Service.Name:", configData.Service.Name)
	return nil
}


watch

	viper.WatchConfig()
	viper.OnConfigChange(func(e fsnotify.Event) {
		fmt.Println("Config file changed:", e.Name)
		if err := viper.Unmarshal(&Topics); err != nil {
			// return err
		}
	})

reference

Last updated