From 42a499d7ac2c02fe711ff1d29d45aa57cbff8edb Mon Sep 17 00:00:00 2001 From: Albert Vaca Date: Tue, 26 Mar 2019 15:14:00 +0100 Subject: [PATCH] Warn when a yaml file has duplicated keys Try using `UnmarshalStrict`, if it fails, print the errors as a warning and try again with plain `Unmarshal`. Errors look this way: ``` 2019/03/26 15:11:33 warning reading config file: yaml: unmarshal errors: line 6: key "api_key" already set in map ``` --- viper.go | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/viper.go b/viper.go index c8044e1..b098dc8 100644 --- a/viper.go +++ b/viper.go @@ -1462,8 +1462,12 @@ func (v *Viper) unmarshalReader(in io.Reader, c map[string]interface{}) error { switch strings.ToLower(v.getConfigType()) { case "yaml", "yml": - if err := yaml.Unmarshal(buf.Bytes(), &c); err != nil { - return ConfigParseError{err} + // Try UnmarshalStrict first, so we can warn about duplicated keys + if strictErr := yaml.UnmarshalStrict(buf.Bytes(), &c); strictErr != nil { + if err := yaml.Unmarshal(buf.Bytes(), &c); err != nil { + return ConfigParseError{err} + } + log.Printf("warning reading config file: %v\n", strictErr) } case "json":