-
-
Notifications
You must be signed in to change notification settings - Fork 106
/
patch.go
53 lines (43 loc) · 1.05 KB
/
patch.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
package jsonx
import (
"encoding/json"
"fmt"
jsonpatch "github.com/evanphx/json-patch"
)
var opAllowList = map[string]struct{}{
"add": {},
"remove": {},
"replace": {},
}
func ApplyJSONPatch(p json.RawMessage, object interface{}, denyPaths ...string) error {
patch, err := jsonpatch.DecodePatch(p)
if err != nil {
return err
}
denySet := make(map[string]struct{})
for _, path := range denyPaths {
denySet[path] = struct{}{}
}
for _, op := range patch {
// Some operations are buggy, see https://github.com/evanphx/json-patch/pull/158
if _, ok := opAllowList[op.Kind()]; !ok {
return fmt.Errorf("unsupported operation: %s", op.Kind())
}
path, err := op.Path()
if err != nil {
return fmt.Errorf("error parsing patch operations: %v", err)
}
if _, ok := denySet[path]; ok {
return fmt.Errorf("patch includes denied path: %s", path)
}
}
original, err := json.Marshal(object)
if err != nil {
return err
}
modified, err := patch.Apply(original)
if err != nil {
return err
}
return json.Unmarshal(modified, object)
}