Gin and your data · 6 MIN READ
PATCH with JSON Merge Patch in Gin: keep absent, null and value apart, then validate the merged resource
Implement an RFC 7396 merge-patch endpoint in Gin that distinguishes absent from null, enforces application/merge-patch+json with 415, and validates the merged result before storing it.
A client that wants to clear a due date sends {"due": null}; a client that only renames a note leaves due out entirely. If the server cannot tell those requests apart, it either ignores the clear or wipes a field nobody mentioned. JSON Merge Patch gives the three cases exact meanings, and Gin's struct binding cannot see one of them.
gin · A MAP OF THE IDEA
- Require merge-patch type
- Decode to a generic map
- Merge into current doc
- Decode strictly, validate
Useful when
- Clients can leave, clear or replace each member exactly as RFC 7396 defines.
- Validation sees the resource the store will hold, not a fragment of it.
Watch out
- Arrays are replaced whole and null cannot be stored as a value; use JSON Patch when that matters.
- Read, merge and write still need If-Match or a version check across replicas.
Implementation & operation cost: A generic decode, a merge and a second strict decode per request, plus media-type checks and error mapping that plain struct binding does not need.
Three meanings in one small document
RFC 7396 defines a merge patch as a JSON document that mirrors the target. For each member of a patch object, an absent member leaves the target alone, null removes the member, an object merges recursively, and any other value, arrays included, replaces the member whole. A patch that is not an object replaces the entire target. The media type is application/merge-patch+json, and claiming merge-patch semantics means honoring all of these rules, not just the convenient ones. The crud-resource lesson used pointer fields for PATCH and noted that they cannot express removal; this lesson builds the full version, including nested objects, strict decoding and the error statuses a client can program against.
Why struct binding cannot hear null
encoding/json sets a pointer field to nil when the member is null, and nil is also what an absent member leaves behind, so {} and {"due":null} bind to identical structs. ShouldBindJSON adds nothing that helps here: in v1.12.0 it runs a json.Decoder over the body and then the validator, and it never looks at Content-Type. c.ShouldBind is worse for this route, because it picks a binding from Content-Type through binding.Default, and application/merge-patch+json is not in that table, so it falls back to form binding and never decodes the JSON body at all. Two representations keep the information. A map[string]json.RawMessage records presence as a key and null as the four raw bytes null. A small tri-state type with an UnmarshalJSON method works too, because encoding/json calls UnmarshalJSON for a present null but not for an absent member.
Merge, decode strictly, validate
The program first decodes the same three bodies into a pointer field and into a raw map, so the difference is visible. The handler then checks the media type, decodes the patch generically, refuses members a client may not change, and merges the patch into the current note represented as a generic JSON document. It turns the merged document back into a Note with unknown fields disallowed and validates that Note with Gin's validator before storing it.
package main
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"mime"
"net/http"
"net/http/httptest"
"strings"
"sync"
"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
"github.com/go-playground/validator/v10"
)
type Settings struct {
Color string `json:"color,omitempty" binding:"omitempty,oneof=red blue green"`
Pinned bool `json:"pinned"`
}
type Note struct {
ID int `json:"id"`
Title string `json:"title" binding:"required,max=40"`
Due string `json:"due,omitempty" binding:"omitempty,datetime=2006-01-02"`
Tags []string `json:"tags,omitempty" binding:"max=3,dive,min=1,max=12"`
Settings Settings `json:"settings"`
}
// patchable lists the top-level members a client may change; id is read-only.
var patchable = map[string]bool{"title": true, "due": true, "tags": true, "settings": true}
// mergePatch is the algorithm of RFC 7396, section 2: objects merge member by
// member, null removes a member, and anything else replaces the target.
func mergePatch(target, patch any) any {
p, ok := patch.(map[string]any)
if !ok {
return patch
}
t, ok := target.(map[string]any)
if !ok {
t = map[string]any{}
}
for k, v := range p {
if v == nil {
delete(t, k)
} else {
t[k] = mergePatch(t[k], v)
}
}
return t
}
// decodeOne reads exactly one JSON value and keeps numbers exact.
func decodeOne(r io.Reader, v any) error {
dec := json.NewDecoder(r)
dec.UseNumber()
if err := dec.Decode(v); err != nil {
return err
}
if err := dec.Decode(new(any)); err != io.EOF {
return errors.New("trailing data after the JSON value")
}
return nil
}
func apply(current Note, patch any) (Note, error) {
doc, _ := json.Marshal(current)
var target any
if err := decodeOne(bytes.NewReader(doc), &target); err != nil {
return Note{}, err
}
merged, _ := json.Marshal(mergePatch(target, patch))
dec := json.NewDecoder(bytes.NewReader(merged))
dec.DisallowUnknownFields()
var next Note
if err := dec.Decode(&next); err != nil {
return Note{}, err
}
return next, binding.Validator.ValidateStruct(&next) // validate the result, not the patch
}
func newRouter() *gin.Engine {
var mu sync.Mutex
notes := map[int]Note{7: {ID: 7, Title: "Ship v2", Due: "2026-12-01",
Tags: []string{"go", "api"}, Settings: Settings{Color: "blue", Pinned: true}}}
r := gin.New()
r.PATCH("/notes/7", func(c *gin.Context) {
mt, _, err := mime.ParseMediaType(c.GetHeader("Content-Type"))
if err != nil || mt != "application/merge-patch+json" {
c.Header("Accept-Patch", "application/merge-patch+json")
c.AbortWithStatusJSON(http.StatusUnsupportedMediaType, gin.H{"error": "use application/merge-patch+json"})
return
}
var patch any
if err := decodeOne(http.MaxBytesReader(c.Writer, c.Request.Body, 16<<10), &patch); err != nil {
c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "malformed JSON"})
return
}
obj, ok := patch.(map[string]any)
if !ok {
c.AbortWithStatusJSON(http.StatusUnprocessableEntity, gin.H{"error": "patch must be a JSON object"})
return
}
for k := range obj {
if !patchable[k] {
c.AbortWithStatusJSON(http.StatusUnprocessableEntity, gin.H{"error": "member not patchable: " + k})
return
}
}
mu.Lock()
defer mu.Unlock()
next, err := apply(notes[7], patch)
var invalid validator.ValidationErrors
switch {
case errors.As(err, &invalid):
fields := make([]string, len(invalid))
for i, fe := range invalid {
fields[i] = fe.Namespace() + " " + fe.Tag()
}
c.AbortWithStatusJSON(http.StatusUnprocessableEntity, gin.H{"error": "invalid result", "fields": fields})
return
case err != nil:
c.AbortWithStatusJSON(http.StatusUnprocessableEntity, gin.H{"error": err.Error()})
return
}
notes[7] = next
c.JSON(http.StatusOK, next)
})
return r
}
type pointerDTO struct {
Title *string `json:"title"`
}
func main() {
gin.SetMode(gin.TestMode)
fmt.Println("what each decoding target can see:")
for _, body := range []string{`{}`, `{"title":null}`, `{"title":"x"}`} {
var dto pointerDTO
_ = json.Unmarshal([]byte(body), &dto)
var raw map[string]json.RawMessage
_ = json.Unmarshal([]byte(body), &raw)
pointer, member := "nil", "absent"
if dto.Title != nil {
pointer = fmt.Sprintf("%q", *dto.Title)
}
if m, ok := raw["title"]; ok {
member = string(m)
}
fmt.Printf(" %-16s pointer field: %-5s map member: %s\n", body, pointer, member)
}
r := newRouter()
send := func(contentType, body string) {
req := httptest.NewRequest(http.MethodPatch, "/notes/7", strings.NewReader(body))
req.Header.Set("Content-Type", contentType)
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
fmt.Printf("PATCH %s\n %d %s\n", body, w.Code, w.Body.String())
if v := w.Header().Get("Accept-Patch"); v != "" {
fmt.Println(" Accept-Patch:", v)
}
}
const mp = "application/merge-patch+json"
send(mp, `{"due":null,"tags":["go"]}`)
send("Application/Merge-Patch+JSON", `{"title":"Ship v2.1","settings":{"color":null}}`)
send(mp, `{"title":null}`)
send(mp, `{"id":8}`)
send(mp, `{"settings":{"colour":"red"}}`)
send(mp, `{"tags":["go"]} {"tags":[]}`)
send("application/json", `{"title":"Ship v3"}`)
}The pointer is nil for both {} and null, while the map distinguishes absent from null. mime.ParseMediaType lowercases the type and drops parameters, so Application/Merge-Patch+JSON is accepted; c.ContentType() only strips parameters, so comparing its result to a lowercase constant would reject that client. decodeOne reads one value, keeps numbers as json.Number so large integers survive the round trip, and rejects trailing data, which is why the body with two objects is a 400. mergePatch is the RFC 7396 algorithm. Decoding the merged document with DisallowUnknownFields refuses a misspelled nested member such as colour instead of dropping it. Removing due makes it absent, and omitempty keeps it absent on output. {"title":null} removes a required member, so validating the merged note gives 422 naming the field. The 415 carries Accept-Patch, as RFC 5789 recommends.
Validate the result, not the patch
Whether a patch is acceptable depends on the state it lands on. {"title":null} is a perfectly formed patch that removes a required member, and a tag limit applies to the merged list, not to the members a client happened to send. So the rules live on the resource struct and run on the merged value through binding.Validator.ValidateStruct, the same validator ShouldBindJSON would have used. Read-only members such as id are refused before merging, because a merge would otherwise apply them. Pick statuses clients can act on: 415 with Accept-Patch for the wrong media type, 400 for malformed JSON, 422 for a well-formed patch that is not allowed or produces an invalid resource. The mutex makes read, merge and write one step inside this process. Across replicas the same read-modify-write needs a version check, and the optimistic-concurrency lesson adds If-Match for exactly this endpoint.
A tri-state field when you prefer a typed DTO
A generic merge suits resources whose JSON shape matches the stored model. When the public shape differs, or only a few members are patchable, a typed patch DTO reads better. Optional records presence and null separately, and ShouldBindJSON can still decode it because it simply runs encoding/json. Apply the DTO to a copy of the stored resource, then validate the copy exactly as before.
// Optional records whether a member was present and whether it was null.
type Optional[T any] struct {
Set bool // the member appeared in the patch
Null bool // it appeared as JSON null
Value T // the zero value when Null is true
}
func (o *Optional[T]) UnmarshalJSON(b []byte) error {
o.Set = true // encoding/json calls this only for members that are present
if string(b) == "null" {
o.Null = true
return nil
}
return json.Unmarshal(b, &o.Value)
}
type notePatch struct {
Title Optional[string] `json:"title"`
Due Optional[string] `json:"due"`
}
// applyTo edits a copy of the stored note; validate the result afterwards.
func (p notePatch) applyTo(n Note) Note {
if p.Title.Set {
n.Title = p.Title.Value // null gives "", which the required rule rejects
}
if p.Due.Set {
n.Due = p.Due.Value // null clears the due date
}
return n
}This fragment plugs into the program's Note type; compile it inside your own service. UnmarshalJSON is never called for an absent member, so Set stays false and applyTo leaves the field alone. For a present null, encoding/json passes the literal bytes null, so Null is set and Value keeps its zero value. Validator tags cannot see inside Optional, which is one more reason to validate the patched Note rather than the DTO. Nested objects need their own Optional fields, or a map, to keep merge semantics below the top level.
What a reviewer should still look for
Go's decoder matches member names to struct fields case-insensitively, so {"Title":"x"} binds to Title even though the allow-list map checks exact names; decide which behavior is your contract and test it. For duplicate names, encoding/json keeps the last one, and another parser in front of you may keep the first, so a proxy that inspects patches can see a different document from the one you apply. Merge patch also has two semantic gaps: an array can only be replaced whole, so appending one tag means sending the full list, and null can never be stored as a value. When clients need either, use JSON Patch (RFC 6902) or a sub-resource such as POST /notes/7/tags. Cap the body with http.MaxBytesReader, as the binding-limits lesson explains. The test table writes itself: absent, null, value, nested null, a non-object patch, an unknown member, an invalid result and the wrong media type.
TAKE THIS WITH YOU
Accept only application/merge-patch+json, decode the patch into a representation that keeps absent and null apart, merge it into the current resource, and validate the merged result before storing it.
Check your understanding
A PATCH handler binds {"due": null} with ShouldBindJSON into a struct whose Due field is *string. Why can it not clear the due date correctly?
Go to the source
Progress stays in this browser. No account needed.