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

Using decoder functions for unmanaged struct fields #65

Closed
wants to merge 1 commit into from
Closed
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
6 changes: 5 additions & 1 deletion envconfig.go
Original file line number Diff line number Diff line change
Expand Up @@ -335,7 +335,11 @@ func processWith(ctx context.Context, i interface{}, l Lookuper, parentNoInit bo
return fmt.Errorf("%s: %w", tf.Name, err)
}

if found || usedDefault {
// When the env tag is not present on a struct field, the field is considered
// unmanaged and initialization should always occur through the decoder.
// Managed fields that have the env tag present will only use the decoder
// functions when a variable is set or there is a default.
if found || usedDefault || tag == "" {
if ok, err := processAsDecoder(val, ef); ok {
if err != nil {
return err
Expand Down
39 changes: 39 additions & 0 deletions envconfig_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,31 @@ func (c *CustomStdLibDecodingType) GobDecode(data []byte) error {
return nil
}

var (
_ encoding.TextUnmarshaler = (*TextUnmarshalerType)(nil)
)

// TextUnmarshalerType demonstrates a type that contains a struct pointer with
// no managed env tag. Nested types with no env tag should always defer to the
// decoder for unmarshalling.
type TextUnmarshalerType struct {
ExportedNameWrapper *NameWrapper
}

func (t *TextUnmarshalerType) UnmarshalText(text []byte) error {
if len(string(text)) > 0 {
t.ExportedNameWrapper = &NameWrapper{
name: string(text),
}
}

return nil
}

type NameWrapper struct {
name string
}

var (
_ Decoder = (*CustomTypeError)(nil)
_ encoding.BinaryUnmarshaler = (*CustomTypeError)(nil)
Expand Down Expand Up @@ -1401,6 +1426,20 @@ func TestProcessWith(t *testing.T) {
}),
errMsg: "broken",
},
{
name: "custom_decoder/unmanaged_tag_uses_decoder",
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure I understand what this test is testing?

input: &struct {
Field TextUnmarshalerType
}{
Field: TextUnmarshalerType{},
},
exp: &struct {
Field TextUnmarshalerType
}{
Field: TextUnmarshalerType{},
},
lookuper: MapLookuper(map[string]string{}),
},
{
name: "custom_decoder/not_called_on_unset_envvar",
input: &struct {
Expand Down