/
json.go
45 lines (37 loc) · 835 Bytes
/
json.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
package x
import (
"encoding/json"
"fmt"
jsonpatch "github.com/evanphx/json-patch"
)
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 {
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
}
if err := json.Unmarshal(modified, object); err != nil {
return err
}
return nil
}