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

Allow structs without public fields to implement Setter #83

Open
wants to merge 1 commit into
base: master
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
28 changes: 20 additions & 8 deletions cleanenv.go
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
@@ -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