move options to dedicated package
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
This commit is contained in:
@@ -76,6 +76,9 @@ func ZeroFieldByPath(src interface{}, path string) error {
|
||||
val := reflect.ValueOf(src)
|
||||
|
||||
for _, p := range strings.Split(path, ".") {
|
||||
if p == "" {
|
||||
continue
|
||||
}
|
||||
val, err = structValueByName(val, p)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -101,6 +104,9 @@ func SetFieldByPath(src interface{}, dst interface{}, path string) error {
|
||||
val := reflect.ValueOf(src)
|
||||
|
||||
for _, p := range strings.Split(path, ".") {
|
||||
if p == "" {
|
||||
continue
|
||||
}
|
||||
val, err = structValueByName(val, p)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -111,7 +117,20 @@ func SetFieldByPath(src interface{}, dst interface{}, path string) error {
|
||||
return ErrInvalidStruct
|
||||
}
|
||||
|
||||
val.Set(reflect.ValueOf(dst))
|
||||
nv := reflect.ValueOf(dst)
|
||||
if val.Kind() != nv.Kind() {
|
||||
switch {
|
||||
default:
|
||||
val.Set(nv)
|
||||
case nv.Kind() == reflect.Slice:
|
||||
val.Set(nv.Index(0))
|
||||
case val.Kind() == reflect.Slice:
|
||||
val.Set(reflect.MakeSlice(val.Type(), 1, 1))
|
||||
val.Index(0).Set(nv)
|
||||
}
|
||||
} else {
|
||||
val.Set(nv)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -157,6 +176,9 @@ func structValueByName(sv reflect.Value, tkey string) (reflect.Value, error) {
|
||||
func StructFieldByPath(src interface{}, path string) (interface{}, error) {
|
||||
var err error
|
||||
for _, p := range strings.Split(path, ".") {
|
||||
if p == "" {
|
||||
continue
|
||||
}
|
||||
src, err = StructFieldByName(src, p)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
@@ -62,6 +62,42 @@ func TestStructFieldsNested(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestSetFieldByPathMultiple(t *testing.T) {
|
||||
var err error
|
||||
tv := "test_val"
|
||||
type Str1 struct {
|
||||
Name []string `json:"name"`
|
||||
}
|
||||
val1 := &Str1{}
|
||||
|
||||
err = rutil.SetFieldByPath(val1, tv, ".Name")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if len(val1.Name) != 1 {
|
||||
t.Fatal("assign error")
|
||||
} else if val1.Name[0] != tv {
|
||||
t.Fatal("assign error")
|
||||
}
|
||||
|
||||
type Str2 struct {
|
||||
Name string `json:"name"`
|
||||
}
|
||||
val2 := &Str2{}
|
||||
|
||||
err = rutil.SetFieldByPath(val2, []string{tv}, ".Name")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if len(val1.Name) != 1 {
|
||||
t.Fatal("assign error")
|
||||
} else if val1.Name[0] != tv {
|
||||
t.Fatal("assign error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSetFieldByPath(t *testing.T) {
|
||||
type NestedStr struct {
|
||||
BBB string `json:"bbb"`
|
||||
|
Reference in New Issue
Block a user