forked from grpc-ecosystem/grpc-gateway
-
Notifications
You must be signed in to change notification settings - Fork 0
/
fieldmask_helper.go
55 lines (46 loc) · 1.1 KB
/
fieldmask_helper.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package server
import (
"log"
"reflect"
"strings"
"google.golang.org/genproto/protobuf/field_mask"
)
func applyFieldMask(patchee, patcher interface{}, mask *field_mask.FieldMask) {
if mask == nil {
return
}
for _, path := range mask.GetPaths() {
val := getField(patcher, path)
if val.IsValid() {
setValue(patchee, val, path)
}
}
}
func getField(obj interface{}, path string) (val reflect.Value) {
// this func is lazy -- if anything bad happens just return nil
defer func() {
if r := recover(); r != nil {
log.Printf("failed to get field:\npath: %q\nobj: %#v\nerr: %v", path, obj, r)
val = reflect.Value{}
}
}()
v := reflect.ValueOf(obj)
if len(path) == 0 {
return v
}
for _, s := range strings.Split(path, ".") {
if v.Kind() == reflect.Ptr {
v = reflect.Indirect(v)
}
v = v.FieldByName(s)
}
return v
}
func setValue(obj interface{}, newValue reflect.Value, path string) {
defer func() {
if r := recover(); r != nil {
log.Printf("failed to set value:\nnewValue: %#v\npath: %q\nobj: %#v\nerr: %v", newValue, path, obj, r)
}
}()
getField(obj, path).Set(newValue)
}