util/reflect: fix reflect methods

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
This commit is contained in:
Василий Толстов 2021-10-27 12:55:48 +03:00
parent 45f30c0be3
commit 07d4085201
2 changed files with 15 additions and 18 deletions

View File

@ -75,7 +75,7 @@ func ZeroFieldByPath(src interface{}, path string) error {
val := reflect.ValueOf(src)
for _, p := range strings.Split(path, ".") {
val, err = structValueByName(reflect.ValueOf(val), p)
val, err = structValueByName(val, p)
if err != nil {
return err
}
@ -182,9 +182,6 @@ func StructFieldByName(src interface{}, tkey string) (interface{}, error) {
continue
}
if fld.Name == tkey || strings.EqualFold(strings.ToLower(fld.Name), strings.ToLower(tkey)) {
if val.Kind() != reflect.Ptr && val.CanAddr() {
val = val.Addr()
}
return val.Interface(), nil
}

View File

@ -10,17 +10,17 @@ import (
func TestSetFieldByPath(t *testing.T) {
type NestedStr struct {
BBB string
CCC int
BBB string `json:"bbb"`
CCC int `json:"ccc"`
}
type Str1 struct {
Name []string `json:"name" codec:"flatten"`
XXX string `json:"xxx"`
Nested NestedStr
Nested NestedStr `json:"nested"`
}
type Str2 struct {
XXX string `json:"xxx"`
Nested *NestedStr
Nested *NestedStr `json:"nested"`
Name []string `json:"name" codec:"flatten"`
}
var err error
@ -44,27 +44,27 @@ func TestSetFieldByPath(t *testing.T) {
func TestZeroFieldByPath(t *testing.T) {
type NestedStr struct {
BBB string
CCC int
BBB string `json:"bbb"`
CCC int `json:"ccc"`
}
type Str1 struct {
Name []string `json:"name" codec:"flatten"`
XXX string `json:"xxx"`
Nested NestedStr
Nested NestedStr `json:"nested"`
}
type Str2 struct {
XXX string `json:"xxx"`
Nested *NestedStr
Nested *NestedStr `json:"nested"`
Name []string `json:"name" codec:"flatten"`
}
var err error
val1 := &Str1{Name: []string{"first", "second"}, XXX: "ttt", Nested: NestedStr{BBB: "ddd", CCC: 9}}
err = rutil.ZeroFieldByPath(val1, "name.nested.bbb")
err = rutil.ZeroFieldByPath(val1, "Nested.BBB")
if err != nil {
t.Fatal(err)
}
err = rutil.ZeroFieldByPath(val1, "name.nested")
err = rutil.ZeroFieldByPath(val1, "Nested")
if err != nil {
t.Fatal(err)
}
@ -73,7 +73,7 @@ func TestZeroFieldByPath(t *testing.T) {
}
val2 := &Str2{Name: []string{"first", "second"}, XXX: "ttt", Nested: &NestedStr{BBB: "ddd", CCC: 9}}
err = rutil.ZeroFieldByPath(val2, "name.nested")
err = rutil.ZeroFieldByPath(val2, "Nested")
if err != nil {
t.Fatal(err)
}
@ -182,9 +182,9 @@ func TestStructByName(t *testing.T) {
t.Fatal(err)
}
if v, ok := iface.(*[]string); !ok {
t.Fatalf("not *[]string %v", iface)
} else if len(*v) != 2 {
if v, ok := iface.([]string); !ok {
t.Fatalf("not []string %v", iface)
} else if len(v) != 2 {
t.Fatalf("invalid number %v", iface)
}
}