add ChainMergeConfigFiles

This commit is contained in:
satotake 2017-04-03 02:11:29 +09:00
parent 84f94806c6
commit 1b560de7b7

View file

@ -147,6 +147,7 @@ type Viper struct {
// Name of file to look for inside the path // Name of file to look for inside the path
configName string configName string
configFile string configFile string
configFiles []string
configType string configType string
envPrefix string envPrefix string
@ -291,6 +292,15 @@ func (v *Viper) SetConfigFile(in string) {
} }
} }
// SetConfigFiles explicitly defines slice of the path, name and extension of the config files
// Viper will use these and not check any of the config paths
func SetConfigFiles(in []string) { v.SetConfigFiles(in) }
func (v *Viper) SetConfigFiles(in []string) {
if len(in) > 0 {
v.configFiles = in
}
}
// SetEnvPrefix defines a prefix that ENVIRONMENT variables will use. // SetEnvPrefix defines a prefix that ENVIRONMENT variables will use.
// E.g. if your prefix is "spf", the env registry // E.g. if your prefix is "spf", the env registry
// will look for env. variables that start with "SPF_" // will look for env. variables that start with "SPF_"
@ -1131,8 +1141,29 @@ func (v *Viper) MergeInConfig() error {
return v.MergeConfig(bytes.NewReader(file)) return v.MergeConfig(bytes.NewReader(file))
} }
// ReadConfig will read a configuration file, setting existing keys to nil if the // ChainMergeConfigfiles repeatedly merge with configFiles
// key does not exist in the file. func ChainMergeConfigFiles() error { return v.ChainMergeConfigFiles() }
func (v *Viper) ChainMergeConfigFiles() error {
jww.INFO.Println("Attempting to chain merge with configFiles")
for i, filename := range v.configFiles {
if i == 0 {
v.SetConfigFile(filename)
err := v.ReadInConfig()
if err != nil {
return err
}
} else {
v.SetConfigFile(filename)
err := v.MergeInConfig()
if err != nil {
return err
}
}
}
return nil
}
func ReadConfig(in io.Reader) error { return v.ReadConfig(in) } func ReadConfig(in io.Reader) error { return v.ReadConfig(in) }
func (v *Viper) ReadConfig(in io.Reader) error { func (v *Viper) ReadConfig(in io.Reader) error {
v.config = make(map[string]interface{}) v.config = make(map[string]interface{})