Skip to content

Commit

Permalink
fix unmarshal error when the tag contains omitempty (#15)
Browse files Browse the repository at this point in the history
* fix unmarshal error when the tag contains omitempty
  • Loading branch information
garenchan authored Sep 13, 2023
1 parent adc194f commit 66e9666
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 5 deletions.
19 changes: 16 additions & 3 deletions enviper.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
21 changes: 19 additions & 2 deletions enviper_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down Expand Up @@ -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 {
Expand Down
3 changes: 3 additions & 0 deletions fixture_env
Original file line number Diff line number Diff line change
Expand Up @@ -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

0 comments on commit 66e9666

Please sign in to comment.