Skip to content
This repository was archived by the owner on Aug 22, 2019. It is now read-only.

Commit

Permalink
Fix: ignore nested struct tags too (#3)
Browse files Browse the repository at this point in the history
  • Loading branch information
tizz98 authored Jun 15, 2019
1 parent 0c78872 commit dd711f4
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 7 deletions.
15 changes: 10 additions & 5 deletions config.go
Original file line number Diff line number Diff line change
Expand Up @@ -158,11 +158,12 @@ func (c *Builder) populateStructRecursively(structPtr interface{}, prefix string
fieldType := structValue.Type().Field(i)
fieldPtr := structValue.Field(i).Addr().Interface()

key := getKey(fieldType, prefix)
if key == structTagIgnoreField {
possibleKey := getKey(fieldType, prefix)
if possibleKey == nil {
continue
}

key := *possibleKey
value := c.configMap[key]

switch fieldType.Type.Kind() {
Expand All @@ -179,14 +180,18 @@ func (c *Builder) populateStructRecursively(structPtr interface{}, prefix string
// getKey returns the string that represents this structField in the config map.
// If the structField has the appropriate structTag set, it is used.
// Otherwise, field's name is used.
func getKey(t reflect.StructField, prefix string) string {
func getKey(t reflect.StructField, prefix string) *string {
name := t.Name
if tag, exists := t.Tag.Lookup(structTagKey); exists {
if tag = strings.TrimSpace(tag); tag != "" {
if tag = strings.TrimSpace(tag); tag == structTagIgnoreField {
return nil
} else if tag != "" {
name = tag
}
}
return strings.ToLower(prefix + name)

key := strings.ToLower(prefix + name)
return &key
}

// stringToSlice converts a string to a slice of string, using delim.
Expand Down
11 changes: 9 additions & 2 deletions config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -382,26 +382,33 @@ func Test_getKey(t *testing.T) {
tt := tt
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
if got := getKey(tt.args.t, tt.args.prefix); got != tt.want {
if got := getKey(tt.args.t, tt.args.prefix); *got != tt.want {
t.Errorf("getKey() = %v, want %v", got, tt.want)
}
})
}
}

func Test_structTagIgnore(t *testing.T) {
type B struct {
Foo *string `config:"-"`
Baz string
}
type C struct {
B B
Foo *string `config:"-"`
Bar string
}

require.NoError(t, os.Setenv("FOO", "something"))
require.NoError(t, os.Setenv("B__FOO", "bar"))
require.NoError(t, os.Setenv("B__BAZ", "baz"))
require.NoError(t, os.Setenv("BAR", "baz"))

var got C
want := C{
Foo: nil,
Bar: "baz",
B: B{Baz: "baz"},
}

FromEnv().To(&got)
Expand Down

0 comments on commit dd711f4

Please sign in to comment.