oag
oag copied to clipboard
Support JSON Merge Patch semantics
PATCH
is commonly used to do partial updates of resources, particularly via JSON Merge Patch.
To do a PATCH
like this, we need to support:
- sending a value on a field to update that field
- omitting a field entirely, to skip changing its value
- sending an explicit JSON
null
for a field, to unset it
Implement support for this.
If the resource to be patched looks like:
type Cat struct {
Name string `json:"name"`
Nickname string `json:"nickname"`
}
Then the payload for patching should look like:
type UpdateCat struct {
Name *string `json:"name,omitempty"`
Nickname *string `json:"nickname,omitempty"`
}
// NullString is a magic value used for explicitly sending null in JSON Merge Patch requests
var NullString *string
// String returns a pointer to the provided string
func String(s string) *string { return &s }
UpdateCat will then need a MarshalJSON func, which is aware of NullString, and can explicitly send null
when Name
or Nickname
== NullString
.
Change the value of Name
, and unset Nickname
:
uc := UpdateCat{
Name: pkg.String("Mittens"),
Nickname: pkg.NullString,
}
// pass in to API call
Change the value of Nickname, but leave Name as is:
uc := UpdateCat{NickName: pkg.String("Little Fuzz Monster")}
// pass in to API call