From 5fdf8eb0756f0d074ce208d955e7bc14c81e6622 Mon Sep 17 00:00:00 2001 From: BaaRai <130491490+BaaRai@users.noreply.github.com> Date: Tue, 17 Nov 2026 22:19:59 +0100 Subject: [PATCH] fix(server): keep the MaxBytesError so a caller's 413 mapping still works A handler that installs its own MaxBytesReader and then calls decode lost the 413: decode converted the error to a plain one and the middleware's limitedBody had been replaced. Return the original *http.MaxBytesError and update the cap test to errors.As. --- server/decode_limit_test.go | 3 ++- server/server_mgmt.go | 8 +++----- 2 files changed, 5 insertions(+), 6 deletions(-) diff --git a/server/decode_limit_test.go b/server/decode_limit_test.go index dc8dd08..5922673 100644 --- a/server/decode_limit_test.go +++ b/server/decode_limit_test.go @@ -24,7 +24,8 @@ func TestDecodeCapsBody(t *testing.T) { r := httptest.NewRequest(http.MethodPost, "/", body) var v map[string]string err := decode(w, r, &v) - if !errors.Is(err, errBodyTooLarge) { + var tooLarge *http.MaxBytesError + if !errors.As(err, &tooLarge) { t.Fatalf("err=%v, want the body cap", err) } } diff --git a/server/server_mgmt.go b/server/server_mgmt.go index bada08f..0367e46 100644 --- a/server/server_mgmt.go +++ b/server/server_mgmt.go @@ -85,10 +85,6 @@ func pathInt(r *http.Request, name string) (int64, bool) { // by a handler still wins, because it sits inside this one. const decodeMaxBytes = 32 << 20 -// errBodyTooLarge is decode's error for a body past the cap. Callers that answer -// 400 are turned into 413 by limitRequestBody once the read has hit the cap. -var errBodyTooLarge = errors.New("Request body too large") - // limitedBody records a MaxBytesError so a later 400 can be answered as 413. type limitedBody struct { io.ReadCloser @@ -159,7 +155,9 @@ func decode(w http.ResponseWriter, r *http.Request, v any) error { if lb, ok := r.Body.(*limitedBody); ok { lb.tooLarge = true } - return errBodyTooLarge + // Return the original error: a caller that maps 413 itself keeps working, + // and the middleware still rewrites a 400 for callers that do not. + return tooLarge } return err }