From 21a6d386e0142b448939f666ee670c9172679788 Mon Sep 17 00:00:00 2001 From: Davor Plehati Date: Mon, 6 Oct 2025 17:45:27 +0200 Subject: [PATCH] Return 413 Request Entity Too Large when MaxBytesError occurs When `max_request_size` is set and a client sends a payload that exceeds this limit, return a 413 Request Entity Too Large response instead of a generic 500 Internal Server Error. A 413 status code correctly indicates a client-side error, while 500 implies a server-side issue. --- handler/handler.go | 7 ++++++- tests/http_plugin2_test.go | 2 +- tests/http_plugin3_test.go | 2 +- tests/http_plugin_test.go | 2 +- 4 files changed, 9 insertions(+), 4 deletions(-) diff --git a/handler/handler.go b/handler/handler.go index 68aaaa0..cd85dde 100644 --- a/handler/handler.go +++ b/handler/handler.go @@ -137,7 +137,12 @@ func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { req.Close(h.log, r) h.putReq(req) - http.Error(w, errors.E(op, err).Error(), 500) + status := http.StatusInternalServerError + var maxBytesErr *http.MaxBytesError + if stderr.As(err, &maxBytesErr) { + status = http.StatusRequestEntityTooLarge + } + http.Error(w, errors.E(op, err).Error(), status) h.log.Error( "request forming error", zap.Time("start", start), diff --git a/tests/http_plugin2_test.go b/tests/http_plugin2_test.go index 1e18af5..7c2526a 100644 --- a/tests/http_plugin2_test.go +++ b/tests/http_plugin2_test.go @@ -605,7 +605,7 @@ func TestHTTPBigRespMaxReqSize(t *testing.T) { }() assert.NoError(t, err) - assert.Equal(t, 500, r.StatusCode) + assert.Equal(t, http.StatusRequestEntityTooLarge, r.StatusCode) stopCh <- struct{}{} wg.Wait() diff --git a/tests/http_plugin3_test.go b/tests/http_plugin3_test.go index e3aadca..43bb7f7 100644 --- a/tests/http_plugin3_test.go +++ b/tests/http_plugin3_test.go @@ -1152,7 +1152,7 @@ func TestHTTPBigURLEncoded(t *testing.T) { assert.NoError(t, err) _, _ = io.ReadAll(resp.Body) - require.Equal(t, http.StatusInternalServerError, resp.StatusCode) + require.Equal(t, http.StatusRequestEntityTooLarge, resp.StatusCode) t.Cleanup(func() { _ = resp.Body.Close() diff --git a/tests/http_plugin_test.go b/tests/http_plugin_test.go index f817e2e..f172aba 100644 --- a/tests/http_plugin_test.go +++ b/tests/http_plugin_test.go @@ -1786,7 +1786,7 @@ func TestHTTPBigRequestSize(t *testing.T) { assert.NoError(t, err) b, err := io.ReadAll(r.Body) assert.NoError(t, err) - assert.Equal(t, 500, r.StatusCode) + assert.Equal(t, http.StatusRequestEntityTooLarge, r.StatusCode) assert.Equal(t, "serve_http: http: request body too large\n", string(b)) err = r.Body.Close()