Skip to content

Commit

Permalink
Fix nested load config
Browse files Browse the repository at this point in the history
  • Loading branch information
jinzhu committed Nov 18, 2020
1 parent e7bf770 commit 591dd19
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 14 deletions.
18 changes: 18 additions & 0 deletions admin.yml
@@ -0,0 +1,18 @@
top:
- name: Permission
key: author_manage
icon:
children:
- name: My Permission
key: my_author
icon:
children:
- name: Apply
key: author_apply
icon:
- name: My Applies
key: author_apply_record
icon:
- name: My Permission
key: my_author
icon:
16 changes: 16 additions & 0 deletions configor_test.go
Expand Up @@ -665,3 +665,19 @@ func TestConfigFromEnv(t *testing.T) {
t.Error("Failed to load number from env")
}
}

type Menu struct {
Key string `json:"key" yaml:"key"`
Name string `json:"name" yaml:"name"`
Icon string `json:"icon" yaml:"icon"`
Children []Menu `json:"children" yaml:"children"`
}

type MenuList struct {
Top []Menu `json:"top" yaml:"top"`
}

func TestLoadNestedConfig(t *testing.T) {
adminConfig := MenuList{}
New(&Config{Verbose: true}).Load(&adminConfig, "admin.yml")
}
32 changes: 18 additions & 14 deletions utils.go
Expand Up @@ -317,22 +317,26 @@ func (configor *Configor) processTags(config interface{}, prefixes ...string) er
}
}
} else {
// load slice from env
newVal := reflect.New(field.Type().Elem()).Elem()
if newVal.Kind() == reflect.Struct {
idx := 0
for {
newVal = reflect.New(field.Type().Elem()).Elem()
if err := configor.processTags(newVal.Addr().Interface(), append(getPrefixForStruct(prefixes, &fieldStruct), fmt.Sprint(idx))...); err != nil {
return err
} else if reflect.DeepEqual(newVal.Interface(), reflect.New(field.Type().Elem()).Elem().Interface()) {
break
} else {
idx++
field.Set(reflect.Append(field, newVal))
defer func(field reflect.Value, fieldStruct reflect.StructField) {
if !configValue.IsZero() {
// load slice from env
newVal := reflect.New(field.Type().Elem()).Elem()
if newVal.Kind() == reflect.Struct {
idx := 0
for {
newVal = reflect.New(field.Type().Elem()).Elem()
if err := configor.processTags(newVal.Addr().Interface(), append(getPrefixForStruct(prefixes, &fieldStruct), fmt.Sprint(idx))...); err != nil {
return // err
} else if reflect.DeepEqual(newVal.Interface(), reflect.New(field.Type().Elem()).Elem().Interface()) {
break
} else {
idx++
field.Set(reflect.Append(field, newVal))
}
}
}
}
}
}(field, fieldStruct)
}
}
}
Expand Down

0 comments on commit 591dd19

Please sign in to comment.