Skip to content

Commit 7878a2c

Browse files
Skip no exported field on readStructMetadata (#107)
2 parents 3bb055c + cae814f commit 7878a2c

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

cleanenv.go

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -333,7 +333,10 @@ func readStructMetadata(cfgRoot interface{}) ([]structMeta, error) {
333333

334334
// process nested structure (except of supported ones)
335335
if fld := s.Field(idx); fld.Kind() == reflect.Struct {
336-
336+
//skip unexported
337+
if !fld.CanInterface() {
338+
continue
339+
}
337340
// add structure to parsing stack
338341
if _, found := validStructs[fld.Type()]; !found {
339342
prefix, _ := fType.Tag.Lookup(TagEnvPrefix)

cleanenv_test.go

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1187,3 +1187,26 @@ func TestTimeLocation(t *testing.T) {
11871187
t.Errorf("wrong location pointers: got %p, want %p", S.Location, want)
11881188
}
11891189
}
1190+
1191+
func TestSkipUnexportedField(t *testing.T) {
1192+
conf := struct {
1193+
Database struct {
1194+
Host string `yaml:"host" env:"DB_HOST" env-description:"Database host"`
1195+
Port string `yaml:"port" env:"DB_PORT" env-description:"Database port"`
1196+
} `yaml:"database"`
1197+
server struct {
1198+
Host string `yaml:"host" env:"SRV_HOST,HOST" env-description:"Server host" env-default:"localhost"`
1199+
Port string `yaml:"port" env:"SRV_PORT,PORT" env-description:"Server port" env-default:"8080"`
1200+
} `yaml:"server"`
1201+
}{}
1202+
1203+
if err := ReadConfig("example/simple_config/config.yml", &conf); err != nil {
1204+
t.Fatal(err)
1205+
}
1206+
if conf.server.Host != "" || conf.server.Port != "" {
1207+
t.Fatal("unexpect value on unexported fields")
1208+
}
1209+
if conf.Database.Host == "" || conf.Database.Port == "" {
1210+
t.Fatal("expect value on exported fields")
1211+
}
1212+
}

0 commit comments

Comments
 (0)