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,9 +484,37 @@ func (v *Viper) WatchConfig() {
log.Printf("error reading config file: %v\n", err)
}
v.updateRegisteredConfig(tempViper)
if v.onConfigChange != nil {
v.onConfigChange(event)
}
} else if filepath.Clean(event.Name) == configFile && event.Has(fsnotify.Remove) {
eventsWG.Done()
return
}
case err, ok := <-watcher.Errors:
if ok { // 'Errors' channel is not closed
log.Printf("watcher error: %v\n", err)
}
eventsWG.Done()
return
}
}
}()
watcher.Add(configDir)
initWG.Done() // done initializing the watch in this go routine, so the parent routine can move on...
eventsWG.Wait() // now, wait for event loop to end in this go-routine...
}()
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 := tempViper.Get(key)
newValue := newConfigViper.Get(key)
// Check exist
if newValue == nil && !config.CanBeNil {
if config.OnUpdateFailed != nil {
@ -500,7 +528,7 @@ func (v *Viper) WatchConfig() {
// Type check & convert
newValueJson, _ := js.Marshal(newValue)
err = js.Unmarshal(newValueJson, config.Schema)
err := js.Unmarshal(newValueJson, config.Schema)
if err != nil {
config.OnUpdateFailed(&Event{
old: oldValue,
@ -527,29 +555,6 @@ func (v *Viper) WatchConfig() {
})
}
}
if v.onConfigChange != nil {
v.onConfigChange(event)
}
} else if filepath.Clean(event.Name) == configFile && event.Has(fsnotify.Remove) {
eventsWG.Done()
return
}
case err, ok := <-watcher.Errors:
if ok { // 'Errors' channel is not closed
log.Printf("watcher error: %v\n", err)
}
eventsWG.Done()
return
}
}
}()
watcher.Add(configDir)
initWG.Done() // done initializing the watch in this go routine, so the parent routine can move on...
eventsWG.Wait() // now, wait for event loop to end in this go-routine...
}()
initWG.Wait() // make sure that the go routine above fully ended before returning
}
// SetConfigFile explicitly defines the path, name and extension of the config file.