A client sends PATCH /docs/svc-42 with five operations, and the fourth refers to a path that
does not exist. Your handler has already written the first three, so the stored document is
half patched and matches neither version the client knows. A retry of the same patch then fails on
the first operation, because the state it tested has moved.
What you get
You will end up with a Go handler that applies RFC 6902 operations to stored bytes as one unit, refusing the whole patch when any operation fails. This is for you if clients edit JSON documents your service stores.
Short answer
Decode the client’s operations with jsonpatch.DecodePatch from evanphx/json-patch, apply
them to the stored bytes with ApplyWithOptions, and replace the stored document only when
that call returns no error. Patch the bytes, never a struct decoded from them. Turn off negative
indexes, cap copy growth, and answer 409 for a failed test op or a missing path.
You will need
Go 1.24 or later and a handler that reads the request body. Verified 2026-11-29 against Go 1.24.7 and Go 1.25.14 with evanphx/json-patch v5.9.11. The operations and their error rule come from RFC 6902, the paths inside them from RFC 6901, and the status codes from RFC 5789 section 2.2.
Approaches compared
| Approach | When it fits | What it costs you | When to pick something else |
|---|---|---|---|
| evanphx/json-patch | Clients send RFC 6902 operations and you store JSON as bytes | Works on []byte, accepts negative indexes by default, and compares numbers in test by their spelling | Clients only ever replace whole members, so merge patch is enough |
| Hand-rolled JSON Pointer walk over map[string]any | You cannot add a dependency and the documents are small | About 270 lines to own, re-sorted keys, and integers past 2^53 rounded on every write | Documents carry large ids or key order matters to a reader |
| JSON Merge Patch | Clients send a partial document and never edit inside arrays | Cannot change one array element, cannot set a member to null, and has no test op | Clients need a conditional edit or an array edit |
evanphx/json-patch handles pointer escapes, the - index and all six operations, at the price of
two defaults that a public endpoint should override. A hand-rolled walk compares numbers by value because everything
decodes to float64, and it pays for that with lost precision and lost key order. Merge patch is
the simplest for a client to write, but its null means delete.
Apply the patch to the stored bytes
ApplyWithOptions returns a patched copy, and in the tests here it left the stored slice untouched
when an operation failed. Hold one lock across the version check, the apply and the swap, and
store the result only after the call succeeds.
func options() *jsonpatch.ApplyOptions {
o := jsonpatch.NewApplyOptions()
o.SupportNegativeIndices = false // RFC 6901 has no negative index
o.AccumulatedCopySizeLimit = MaxCopyGrowth
o.EscapeHTML = false
return o
}
// update runs fn on the stored bytes and keeps its result only when fn
// returns no error. The lock covers the version check, fn and the swap.
// An empty ifMatch, or "*", skips the version check.
func (s *Store) update(id, ifMatch string, fn func([]byte) ([]byte, error)) ([]byte, string, error) {
s.mu.Lock()
defer s.mu.Unlock()
e, ok := s.docs[id]
if !ok {
return nil, "", ErrNotFound
}
if ifMatch != "" && ifMatch != "*" && ifMatch != etag(e.version) {
return nil, "", ErrStale
}
next, err := fn(e.body)
if err != nil {
return nil, "", err
}
s.docs[id] = entry{body: next, version: e.version + 1}
return append([]byte(nil), next...), etag(e.version + 1), nil
}
// ApplyJSONPatch applies an RFC 6902 patch to the stored bytes.
func (s *Store) ApplyJSONPatch(id, ifMatch string, patchJSON []byte) ([]byte, string, error) {
canon, err := CanonicalNumbers(patchJSON)
if err != nil {
return nil, "", fmt.Errorf("%w: %w", ErrBadPatch, err)
}
patch, err := jsonpatch.DecodePatch(canon)
if err != nil {
return nil, "", fmt.Errorf("%w: %w", ErrBadPatch, err)
}
return s.update(id, ifMatch, func(doc []byte) ([]byte, error) {
next, err := patch.ApplyWithOptions(doc, options())
if err != nil {
return nil, fmt.Errorf("%w: %w", ErrConflict, err)
}
return next, nil
The library’s NewApplyOptions sets SupportNegativeIndices to true, so /tags/-1 removes the
last tag, a reading the RFC 6901 grammar does not allow. AccumulatedCopySizeLimit defaults to
zero, which means no limit, so one patch of repeated copy operations can grow a document without
bound. CanonicalNumbers is the sample’s own function, and the section on failures explains why it is there.
Map the errors to status codes
RFC 5789 suggests 400 for a malformed patch, 409 when the patch cannot apply to the resource’s
state, and 415 with an Accept-Patch header for a format the server does not take. An If-Match
that names a superseded version gets 412, which RFC 5789 calls the most helpful answer to a failed
precondition and RFC 9110 section 13.1.1 allows.
The handler reads the body through
http.MaxBytesReader and switches on the wrapped
error.
doc, tag, err := apply(r.PathValue("id"), r.Header.Get("If-Match"), body)
switch {
case errors.Is(err, ErrNotFound):
http.Error(w, err.Error(), http.StatusNotFound)
case errors.Is(err, ErrBadPatch):
http.Error(w, err.Error(), http.StatusBadRequest)
case errors.Is(err, ErrConflict):
http.Error(w, err.Error(), http.StatusConflict)
case errors.Is(err, ErrStale):
http.Error(w, err.Error(), http.StatusPreconditionFailed)
case err != nil:
http.Error(w, "internal error", http.StatusInternalServerError)
default:
w.Header().Set("Content-Type", "application/json")
w.Header().Set("ETag", tag)
w.Write(doc)
}
The demo stores one document, serves the handler on a loopback port, and sends five patches. The second replaces the title and then tests a value that no longer holds.
go run .
1. test, then replace, append and remove
200 ETag "v2" {"id":"svc-42","title":"Checkout","tags":["api","ga"],"limits":{"rps":100},"labels":{"team/owner":"checkout"},"x-audit":{"by":"ops"}}
2. replace the title, then a test that fails
409 patch does not apply: testing value /limits/rps failed: test failed
stored document unchanged: true
3. a merge patch
200 ETag "v3" {"id":"svc-42","title":"Checkout v2","tags":["api","ga"],"limits":{"rps":100},"labels":{"team/owner":"checkout"}}
4. a patch in a format the handler does not accept
415 unsupported patch format
5. a patch sent with If-Match naming the first version
412 document has changed since that version
The first patch reached team/owner through the pointer /labels/team~1owner and appended with
/tags/-. The title replace in the second patch ran before the failed test, but the swap never
happened, so the stored document still says Checkout and keeps the ETag value "v2". The merge patch
deleted x-audit by sending it as null. The fifth patch named version one and was refused whole.
Compare the three on one document
The same two edits, through the library, the hand-rolled walk in handrolled/apply.go, and a merge
patch through the library’s MergePatch.
go run ./cmd/compare
stored {"title":"Checkout","tags":["api","beta"],"owner":"ops","seq":9007199254740993}
edit: replace the second tag
library {"title":"Checkout","tags":["api","ga"],"owner":"ops","seq":9007199254740993}
by hand {"owner":"ops","seq":9007199254740992,"tags":["api","ga"],"title":"Checkout"}
merge {"title":"Checkout","tags":["api","ga"],"owner":"ops","seq":9007199254740993}
edit: set owner to null
library {"title":"Checkout","tags":["api","beta"],"owner":null,"seq":9007199254740993}
by hand {"owner":null,"seq":9007199254740992,"tags":["api","beta"],"title":"Checkout"}
merge {"title":"Checkout","tags":["api","beta"],"seq":9007199254740993}
The hand-rolled walk sorted the keys and changed seq, because
encoding/json decodes a number into float64
when the target is any. The merge patch had to send the whole tags array to change one element,
and it removed owner where the other two set it to null, as
RFC 7396 section 2 specifies.1
Check it worked
The tests apply a patch whose test op fails after two operations that succeed, and compare the
stored bytes before and after. Others check the escapes, the refused negative index, the copy
cap, a stale If-Match, each status code, and 50 concurrent appends.
go test -count=1 -v ./... | grep -E '^(=== RUN|--- FAIL|FAIL)'
=== RUN TestPatchingTheBytesKeepsAFieldTheStructLacks
=== RUN TestPatchingADecodedStructDropsTheField
=== RUN TestAgreesWithTheLibrary
=== RUN TestRefusesWhatTheRFCRefuses
=== RUN TestComparesNumbersByValue
=== RUN TestLosesKeyOrderAndIntegersAbove2To53
=== RUN TestAFailedTestOpLeavesTheStoredDocumentUnchanged
=== RUN TestAPassingTestOpLetsThePatchApply
=== RUN TestPointerEscapesAndTheDashIndex
=== RUN TestANegativeIndexIsRefused
=== RUN TestCopyGrowthIsCapped
=== RUN TestNumbersCompareByValueOnlyAfterCanonicalization
=== RUN TestCanonicalNumbersKeepsOrderStringsAndBigIntegers
=== RUN TestAMergePatchNullDeletesTheMember
=== RUN TestConcurrentPatchesAllLand
=== RUN TestHandlerStatusCodes
=== RUN TestIfMatchRefusesAStaleVersion
=== RUN TestAddNeedsTheParentToExist
No FAIL line appears. TestAgreesWithTheLibrary holds the hand-rolled walk to the library’s
result on ten patches, including ~01, which RFC 6901 decodes to ~1 and never to /.2
When it goes wrong
A field disappears after an unrelated patch. The handler decoded the stored document into its read struct, marshaled the struct, and patched that, so every member the struct lacks was gone before the patch ran.
go run ./cmd/pitfall
patched the stored bytes: {"id":"svc-42","title":"Checkout v2","limits":{"rps":50},"x-audit":{"by":"ops"}}
patched a decoded struct: {"id":"svc-42","title":"Checkout v2","limits":{"rps":50}}
Patch the stored bytes, as viaBytes in cmd/pitfall/main.go does, and keep the struct for reads.
A test op fails on a value that matches. RFC 6902 section 4.6 compares numbers by value, but the
library compares the bytes, so a stored 1.50 fails a test for 1.5. The sample rewrites every
number in the stored document and in each patch to one spelling before applying. It works on the
decimal digits rather than through float64, so a 20-digit id keeps its value.
go run ./cmd/numbers
library, bytes as sent: error: testing value /price failed: test failed
library, numbers rewritten: {"sku":"A-1","price":1.75}
by hand: {"price":1.75,"sku":"A-1"}
A 409 with missing value names a parent that does not exist. RFC 6902 requires the parent of an
add target to exist, so /limits/burst/max fails when burst is absent. The library’s
EnsurePathExistsOnAdd option creates the parents, a departure from the RFC to turn on only when
your clients expect it.
When not to do this
Do not accept JSON Patch when every client edit replaces whole members. Merge patch is a partial document that any client can build, and the library applies it with one call.
Do not keep the defaults of NewApplyOptions for patches from outside your service. Negative
indexes and unlimited copy growth are both on until you turn them off.
Do not rely on the mutex in this sample once more than one process writes, because it orders
patches inside one process only. With several instances, the version check in update has to
happen inside the shared store’s own write to give the same guarantee.
Do not hand-roll the walk to avoid a dependency unless you also own a test that compares it with a
reference implementation, as TestAgreesWithTheLibrary does.
Related how-tos
Last verified
Verified 2026-11-29 against Go 1.24.7 and Go 1.25.14 with evanphx/json-patch v5.9.11. Every output block is what the command preceding it printed. All three approaches ran.
Footnotes
-
JSON Merge Patch was published twice in one month. RFC 7386 and RFC 7396 both carry October 2014 in their headers, with the same two authors and the same title, and the header of the second says it obsoletes the first. With leading spaces removed, the two texts differ only in those headers. The algorithm is set out as indented steps with no braces, so the spaces matter. The first edition puts the line that empties a non-object target level with the
ifmeant to guard it. ↩︎ Back to text -
RFC 6901 section 4 spends a whole sentence on the order of two string replacements:
~1becomes/first, then~0becomes~. Done the other way round,~01turns into/. The same section defines-as the member after the last array element, observes that it can therefore never resolve, and leaves its meaning to whichever specification uses pointers. RFC 6902 gave it one in its description ofadd, where the dash appends. ↩︎ Back to text