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.
This commit is contained in:
BaaRai
2026-11-17 22:19:59 +01:00
parent 186594ed3a
commit 5fdf8eb075
2 changed files with 5 additions and 6 deletions
+2 -1
View File
@@ -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)
}
}
+3 -5
View File
@@ -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
}