From c5284b5b3e02caec6c6ad90927e8f0e23946eefa Mon Sep 17 00:00:00 2001 From: cyprinus Date: Mon, 22 May 2023 22:41:19 +0800 Subject: [PATCH] Abstract the validation process as a method. --- viper.go | 91 ++++++++++++++++++++++++++++++-------------------------- 1 file changed, 48 insertions(+), 43 deletions(-) diff --git a/viper.go b/viper.go index 2b86afb..bb8e3c5 100644 --- a/viper.go +++ b/viper.go @@ -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) }