Skip to content
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
28 changes: 20 additions & 8 deletions cleanenv.go
Original file line number Diff line number Diff line change
Expand Up @@ -238,15 +238,27 @@ func readStructMetadata(cfgRoot interface{}) ([]structMeta, error) {

// process nested structure (except of time.Time)
if fld := s.Field(idx); fld.Kind() == reflect.Struct {
// add structure to parsing stack
if fld.Type() != reflect.TypeOf(time.Time{}) {
prefix, _ := fType.Tag.Lookup(TagEnvPrefix)
cfgStack = append(cfgStack, cfgNode{fld.Addr().Interface(), sPrefix + prefix})
continue
// check if type implements a custom setter
canSet := false
if fld.CanInterface() {
if _, ok := fld.Interface().(Setter); ok {
canSet = true
} else if _, ok := fld.Addr().Interface().(Setter); ok {
canSet = true
}
}
// process time.Time
if l, ok := fType.Tag.Lookup(TagEnvLayout); ok {
layout = &l

if !canSet {
// add structure to parsing stack
if fld.Type() != reflect.TypeOf(time.Time{}) {
prefix, _ := fType.Tag.Lookup(TagEnvPrefix)
cfgStack = append(cfgStack, cfgNode{fld.Addr().Interface(), sPrefix + prefix})
continue
}
// process time.Time
if l, ok := fType.Tag.Lookup(TagEnvLayout); ok {
layout = &l
}
}
}

Expand Down
31 changes: 31 additions & 0 deletions example_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package cleanenv_test

import (
"errors"
"flag"
"fmt"
"os"
Expand Down Expand Up @@ -195,6 +196,36 @@ func Example_setter() {
//Output: {Default:test1 Custom:my field is: test2}
}

// MyCustomStruct is an example type with a custom setter on a struct with
// private fields only.
type MyCustomStruct struct {
priv string
}

func (cs *MyCustomStruct) SetValue(s string) error {
if s == "" {
return errors.New("empty value")
}
cs.priv = s
return nil
}

func (cs *MyCustomStruct) String() string {
return cs.priv
}

func Example_structsetter() {
type config struct {
Custom MyCustomStruct `env:"CUSTOM"`
}

var cfg config
os.Setenv("CUSTOM", "test")
cleanenv.ReadEnv(&cfg)
fmt.Println(cfg.Custom.String())
//Output: test
}

// ConfigUpdate is a type with a custom updater
type ConfigUpdate struct {
Default string `env:"DEFAULT"`
Expand Down