...
1 package jsonpatch
2
3 import (
4 "encoding/json"
5
6 "gopkg.in/yaml.v2"
7 )
8
9 type Op string
10
11 const (
12 Add Op = "add"
13 Replace Op = "replace"
14 Remove Op = "remove"
15 )
16
17 type Patch struct {
18 Ops []Operation `json:"patch"`
19 }
20
21 func NewPatch(ops ...Operation) *Patch {
22 return &Patch{
23 Ops: ops,
24 }
25 }
26
27 func (p *Patch) AddOperations(ops ...Operation) {
28 p.Ops = append(p.Ops, ops...)
29 }
30
31 type Operation struct {
32 Op Op `json:"op"`
33 Path string `json:"path"`
34 Value interface{} `json:"value,omitempty"`
35 }
36
37 func (op Operation) MarshalYAML() (interface{}, error) {
38 m := make(map[string]interface{})
39 m["op"] = op.Op
40 m["path"] = op.Path
41 if op.Value != nil {
42
43 valueJSON, err := json.Marshal(op.Value)
44 if err != nil {
45 return nil, err
46 }
47
48 var valueInterface interface{}
49 if err := json.Unmarshal(valueJSON, &valueInterface); err != nil {
50 return nil, err
51 }
52
53 m["value"] = valueInterface
54 }
55 return m, nil
56 }
57
58
59 func (p *Patch) String() (string, error) {
60 opsYAML, err := yaml.Marshal(p.Ops)
61 if err != nil {
62 return "", err
63 }
64 return string(opsYAML), nil
65 }
66
View as plain text