Abstract the validation process as a method.

This commit is contained in:
cyprinus 2023-05-22 22:41:19 +08:00
parent 4bb20e2c5a
commit c5284b5b3e

View file

@ -484,49 +484,7 @@ func (v *Viper) WatchConfig() {
log.Printf("error reading config file: %v\n", err)
}
for key, config := range v.registered {
oldValue := v.Get(key)
newValue := tempViper.Get(key)
// Check exist
if newValue == nil && !config.CanBeNil {
if config.OnUpdateFailed != nil {
config.OnUpdateFailed(&Event{
old: oldValue,
new: nil,
})
}
continue
}
// Type check & convert
newValueJson, _ := js.Marshal(newValue)
err = js.Unmarshal(newValueJson, config.Schema)
if err != nil {
config.OnUpdateFailed(&Event{
old: oldValue,
new: nil,
})
continue
}
// Validation
if !config.Validator(config.Schema) {
config.OnUpdateFailed(&Event{
old: oldValue,
new: nil,
})
continue
}
// Success
v.Set(key, config.Schema)
if config.OnUpdate != nil {
config.OnUpdate(&Event{
new: config.Schema,
old: oldValue,
})
}
}
v.updateRegisteredConfig(tempViper)
if v.onConfigChange != nil {
v.onConfigChange(event)
@ -552,6 +510,53 @@ func (v *Viper) WatchConfig() {
initWG.Wait() // make sure that the go routine above fully ended before returning
}
// updateRegisteredConfig validate the registered config items in the new config, notify user with the hook functions.
func (v *Viper) updateRegisteredConfig(newConfigViper *Viper) {
for key, config := range v.registered {
oldValue := v.Get(key)
newValue := newConfigViper.Get(key)
// Check exist
if newValue == nil && !config.CanBeNil {
if config.OnUpdateFailed != nil {
config.OnUpdateFailed(&Event{
old: oldValue,
new: nil,
})
}
continue
}
// Type check & convert
newValueJson, _ := js.Marshal(newValue)
err := js.Unmarshal(newValueJson, config.Schema)
if err != nil {
config.OnUpdateFailed(&Event{
old: oldValue,
new: nil,
})
continue
}
// Validation
if !config.Validator(config.Schema) {
config.OnUpdateFailed(&Event{
old: oldValue,
new: nil,
})
continue
}
// Success
v.Set(key, config.Schema)
if config.OnUpdate != nil {
config.OnUpdate(&Event{
new: config.Schema,
old: oldValue,
})
}
}
}
// SetConfigFile explicitly defines the path, name and extension of the config file.
// Viper will use this and not check any of the config paths.
func SetConfigFile(in string) { v.SetConfigFile(in) }