util/reflect: ZeroFieldByPath and SetFieldByPath
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
This commit is contained in:
@@ -72,9 +72,10 @@ func StructFieldByTag(src interface{}, tkey string, tval string) (interface{}, e
|
||||
// ZeroFieldByPath clean struct field by its path
|
||||
func ZeroFieldByPath(src interface{}, path string) error {
|
||||
var err error
|
||||
var val reflect.Value
|
||||
val := reflect.ValueOf(src)
|
||||
|
||||
for _, p := range strings.Split(path, ".") {
|
||||
val, err = structValueByName(reflect.ValueOf(src), p)
|
||||
val, err = structValueByName(reflect.ValueOf(val), p)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -93,6 +94,27 @@ func ZeroFieldByPath(src interface{}, path string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// SetFieldByPath set struct field by its path
|
||||
func SetFieldByPath(src interface{}, dst interface{}, path string) error {
|
||||
var err error
|
||||
val := reflect.ValueOf(src)
|
||||
|
||||
for _, p := range strings.Split(path, ".") {
|
||||
val, err = structValueByName(val, p)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
if !val.CanSet() {
|
||||
return ErrInvalidStruct
|
||||
}
|
||||
|
||||
val.Set(reflect.ValueOf(dst))
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// structValueByName get struct field by its name
|
||||
func structValueByName(sv reflect.Value, tkey string) (reflect.Value, error) {
|
||||
if sv.Kind() == reflect.Ptr {
|
||||
|
Reference in New Issue
Block a user