diff --git a/enviper.go b/enviper.go index e14e210..edde5c5 100644 --- a/enviper.go +++ b/enviper.go @@ -85,9 +85,22 @@ func (e *Enviper) bindEnvs(in interface{}, prev ...string) { t := ifv.Type().Field(i) tv, ok := t.Tag.Lookup(e.TagName()) if ok { - if tv == ",squash" { - e.bindEnvs(fv.Interface(), prev...) - continue + if index := strings.Index(tv, ","); index != -1 { + if tv[:index] == "-" { + continue + } + + // If "squash" is specified in the tag, we squash the field down. + if strings.Index(tv[index+1:], "squash") != -1 { + e.bindEnvs(fv.Interface(), prev...) + continue + } + + tv = tv[:index] + } + + if tv == "" { + tv = t.Name } } else { tv = t.Name diff --git a/enviper_test.go b/enviper_test.go index 6db656b..73bb1b6 100644 --- a/enviper_test.go +++ b/enviper_test.go @@ -59,6 +59,20 @@ func (s *UnmarshalSuite) TestOnlyEnvsByCustomTag() { s.Equal("imTheValueByCustomTag", c.TagTest) } +func (s *UnmarshalSuite) TestOnlyEnvsWithTagValue() { + s.setupEnvConfig() + defer s.tearDownEnvConfig() + + var c Config + e := enviper.New(s.v) + e.SetEnvPrefix("PREF") + s.Nil(e.Unmarshal(&c)) + + s.Equal("imTheValueWithOmitempty", c.TagValueWithOmitempty) + s.Equal("imTheValueWithCustomName", c.TagValueWithNameOmitempty) + s.Equal("", c.TagValueWithDash) +} + func (s *UnmarshalSuite) TestOnlyEnvs() { s.setupEnvConfig() defer s.tearDownEnvConfig() @@ -166,8 +180,11 @@ type Config struct { QuxMap map[string]struct { Quuux bool } - QUX `mapstructure:",squash"` - TagTest string `custom_tag:"TAG_TEST"` + QUX `mapstructure:",squash"` + TagTest string `custom_tag:"TAG_TEST"` + TagValueWithOmitempty string `mapstructure:",omitempty"` + TagValueWithNameOmitempty string `mapstructure:"tag_custom_name,omitempty"` + TagValueWithDash string `mapstructure:"-"` } type QUX struct { diff --git a/fixture_env b/fixture_env index bad2d6c..01af644 100644 --- a/fixture_env +++ b/fixture_env @@ -4,3 +4,6 @@ PREF_QUUUX=false PREF_QUXMAP_KEY1_QUUUX=true PREF_QUUUX_PTR_UNSET_VALUE=testptr3 PREF_TAG_TEST=imTheValueByCustomTag +PREF_TAGVALUEWITHOMITEMPTY=imTheValueWithOmitempty +PREF_TAG_CUSTOM_NAME=imTheValueWithCustomName +PREF_TAGVALUEWITHDASH=imTheValueWithDash