mirror of
https://github.com/spf13/viper
synced 2025-05-11 06:37:27 +00:00
Add Overriders
This commit is contained in:
parent
4684cd816f
commit
8160993b1d
1 changed files with 24 additions and 0 deletions
24
viper.go
24
viper.go
|
@ -202,6 +202,8 @@ type Viper struct {
|
|||
// Specific commands for ini parsing
|
||||
iniLoadOptions ini.LoadOptions
|
||||
|
||||
overriders []Overrider
|
||||
|
||||
automaticEnvApplied bool
|
||||
envKeyReplacer StringReplacer
|
||||
allowEmptyEnv bool
|
||||
|
@ -224,6 +226,10 @@ type Viper struct {
|
|||
decoderRegistry *encoding.DecoderRegistry
|
||||
}
|
||||
|
||||
type Overrider interface {
|
||||
Get(lowerCaseKey string) (string, bool)
|
||||
}
|
||||
|
||||
// New returns an initialized Viper instance.
|
||||
func New() *Viper {
|
||||
v := new(Viper)
|
||||
|
@ -1280,6 +1286,14 @@ func (v *Viper) find(lcaseKey string, flagDefault bool) interface{} {
|
|||
return nil
|
||||
}
|
||||
|
||||
if v.overriders != nil && len(v.overriders) != 0 {
|
||||
for _, overrider := range v.overriders {
|
||||
if val, ok := overrider.Get(lcaseKey); ok {
|
||||
return val
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Env override next
|
||||
if v.automaticEnvApplied {
|
||||
// even if it hasn't been registered, if automaticEnv is used,
|
||||
|
@ -1406,6 +1420,16 @@ func (v *Viper) IsSet(key string) bool {
|
|||
return val != nil
|
||||
}
|
||||
|
||||
func AddOverrider(o Overrider) { v.AddOverrider(o) }
|
||||
|
||||
func (v *Viper) AddOverrider(o Overrider) {
|
||||
if v.overriders == nil {
|
||||
v.overriders = []Overrider{}
|
||||
}
|
||||
|
||||
v.overriders = append(v.overriders, o)
|
||||
}
|
||||
|
||||
// AutomaticEnv makes Viper check if environment variables match any of the existing keys
|
||||
// (config, default or flags). If matching env vars are found, they are loaded into Viper.
|
||||
func AutomaticEnv() { v.AutomaticEnv() }
|
||||
|
|
Loading…
Add table
Reference in a new issue