Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix unmarshal error when the tag contains omitempty #15

Merged
merged 2 commits into from
Sep 13, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading