small fixes

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
This commit is contained in:
2022-03-25 14:24:20 +03:00
parent 54c4287fab
commit 2d292db7bd
5 changed files with 51 additions and 27 deletions

View File

@@ -245,8 +245,13 @@ func StructFields(src interface{}) ([]StructField, error) {
switch val.Kind() {
case reflect.Ptr:
// if !val.IsValid()
if reflect.Indirect(val).Kind() == reflect.Struct {
if val.CanSet() && fld.Type.Elem().Kind() == reflect.Struct {
if val.IsNil() {
val.Set(reflect.New(fld.Type.Elem()))
}
}
switch reflect.Indirect(val).Kind() {
case reflect.Struct:
infields, err := StructFields(val.Interface())
if err != nil {
return nil, err
@@ -255,7 +260,7 @@ func StructFields(src interface{}) ([]StructField, error) {
infield.Path = fmt.Sprintf("%s.%s", fld.Name, infield.Path)
fields = append(fields, infield)
}
} else {
default:
fields = append(fields, StructField{Field: fld, Value: val, Path: fld.Name})
}
case reflect.Struct:
@@ -268,6 +273,7 @@ func StructFields(src interface{}) ([]StructField, error) {
fields = append(fields, infield)
}
default:
fields = append(fields, StructField{Field: fld, Value: val, Path: fld.Name})
}
}

View File

@@ -10,22 +10,28 @@ import (
)
func TestStructfields(t *testing.T) {
type NestedConfig struct {
Value string
}
type Config struct {
Time time.Time
Nested *Config
Nested *NestedConfig
Metadata map[string]int
Broker string
Addr []string
Wait time.Duration
Verbose bool
}
cfg := &Config{Nested: &Config{}}
cfg := &Config{Nested: &NestedConfig{}}
fields, err := rutil.StructFields(cfg)
if err != nil {
t.Fatal(err)
}
if len(fields) != 13 {
t.Fatalf("invalid fields number: %v", fields)
if len(fields) != 7 {
for _, field := range fields {
t.Logf("field %#+v\n", field)
}
t.Fatalf("invalid fields number: %d != %d", 7, len(fields))
}
}