Skip to content

Commit

Permalink
handle map types which implement envconfig.Unmarshaler
Browse files Browse the repository at this point in the history
  • Loading branch information
vrischmann committed Nov 5, 2015
1 parent f23b009 commit 940aedf
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
6 changes: 6 additions & 0 deletions envconfig.go
Original file line number Diff line number Diff line change
Expand Up @@ -270,6 +270,12 @@ func isUnmarshaler(t reflect.Type) bool {
func parseValue(v reflect.Value, str string, ctx *context) (err error) {
vtype := v.Type()

// Special case when the type is a map: we need to make the map
switch vtype.Kind() {
case reflect.Map:
v.Set(reflect.MakeMap(vtype))
}

// Special case for Unmarshaler
if isUnmarshaler(vtype) {
return parseWithUnmarshaler(v, str)
Expand Down
19 changes: 19 additions & 0 deletions envconfig_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -547,3 +547,22 @@ func TestLeaveNil(t *testing.T) {
require.Nil(t, err)
require.Nil(t, conf.MySQL)
}

type myMapType map[string]int

func (t *myMapType) Unmarshal(s string) error {
(*t)[s] = 1
return nil
}

func TestParseMapType(t *testing.T) {
var conf struct {
Map myMapType
}

os.Setenv("MAP", "a")

err := envconfig.Init(&conf)
require.Nil(t, err)
require.Equal(t, 1, conf.Map["a"])
}

0 comments on commit 940aedf

Please sign in to comment.