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

Support map[T]encoding.TextUnmarshaler #323

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
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
32 changes: 29 additions & 3 deletions env.go
Original file line number Diff line number Diff line change
Expand Up @@ -699,9 +699,35 @@ func handleMap(field reflect.Value, value string, sf reflect.StructField, funcMa
elemType := sf.Type.Elem()
elemParserFunc, ok := funcMap[elemType]
if !ok {
elemParserFunc, ok = defaultBuiltInParsers[elemType.Kind()]
if !ok {
return newNoParserError(sf)
rawType := elemType
isPtr := reflect.Ptr == rawType.Kind()

if isPtr {
rawType = rawType.Elem()
}

if _, ok := reflect.New(rawType).Interface().(encoding.TextUnmarshaler); ok {
if isPtr {
elemParserFunc = func(v string) (any, error) {
ptr := reflect.New(rawType)
unmarshaler := ptr.Interface().(encoding.TextUnmarshaler)
err := unmarshaler.UnmarshalText([]byte(v))

return unmarshaler, err
}
} else {
elemParserFunc = func(v string) (any, error) {
ptr := reflect.New(rawType)
err := ptr.Interface().(encoding.TextUnmarshaler).UnmarshalText([]byte(v))

return ptr.Elem().Interface(), err
}
}
} else {
elemParserFunc, ok = defaultBuiltInParsers[elemType.Kind()]
if !ok {
return newNoParserError(sf)
}
}
}

Expand Down
28 changes: 28 additions & 0 deletions env_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -456,6 +456,34 @@ func TestParsesEnvInvalidMap(t *testing.T) {
isTrue(t, errors.Is(err, ParseError{}))
}

func TestParseMapOfUnmarshalerValues(t *testing.T) {
type mapOfUnmarshaler map[string]unmarshaler

type config struct {
Durations mapOfUnmarshaler `env:"DURATIONS"`
}

t.Setenv("DURATIONS", "year:8760h")

var cfg config
isNoErr(t, Parse(&cfg))
isEqual(t, mapOfUnmarshaler{"year": {Duration: 365 * 24 * time.Hour}}, cfg.Durations)
}

func TestParseMapOfUnmarshalerPtrs(t *testing.T) {
type mapOfUnmarshaler map[string]*unmarshaler

type config struct {
Durations mapOfUnmarshaler `env:"DURATIONS"`
}

t.Setenv("DURATIONS", "year:8760h")

var cfg config
isNoErr(t, Parse(&cfg))
isEqual(t, mapOfUnmarshaler{"year": {Duration: 365 * 24 * time.Hour}}, cfg.Durations)
}

func TestParseCustomMapType(t *testing.T) {
type custommap map[string]bool

Expand Down
Loading