package jsonpatch import ( "encoding/json" "gopkg.in/yaml.v2" ) type Op string const ( Add Op = "add" Replace Op = "replace" Remove Op = "remove" ) type Patch struct { Ops []Operation `json:"patch"` } func NewPatch(ops ...Operation) *Patch { return &Patch{ Ops: ops, } } func (p *Patch) AddOperations(ops ...Operation) { p.Ops = append(p.Ops, ops...) } type Operation struct { Op Op `json:"op"` Path string `json:"path"` Value interface{} `json:"value,omitempty"` } func (op Operation) MarshalYAML() (interface{}, error) { m := make(map[string]interface{}) m["op"] = op.Op m["path"] = op.Path if op.Value != nil { // marshal op.Value to JSON valueJSON, err := json.Marshal(op.Value) if err != nil { return nil, err } // unmarshal JSON string back to interface{} var valueInterface interface{} if err := json.Unmarshal(valueJSON, &valueInterface); err != nil { return nil, err } // set value to be the unmarshaled interface{} m["value"] = valueInterface } return m, nil } // String converts the Patch to a YAML string func (p *Patch) String() (string, error) { opsYAML, err := yaml.Marshal(p.Ops) if err != nil { return "", err } return string(opsYAML), nil }