From f6c0ff96d82a3c945dbadc03b47c9ec6c5b6da9f Mon Sep 17 00:00:00 2001 From: sb123sb123 <152394158+sb123sb123@users.noreply.github.com> Date: Tue, 22 Sep 2026 13:03:46 +0800 Subject: [PATCH] fix(context): handle nil request body in ShouldBindBodyWith Fixes #1973 --- context.go | 3 +++ context_test.go | 9 +++++++++ 2 files changed, 12 insertions(+) diff --git a/context.go b/context.go index 788b00bb..e09f84ec 100644 --- a/context.go +++ b/context.go @@ -956,6 +956,9 @@ func (c *Context) ShouldBindBodyWith(obj any, bb binding.BindingBody) (err error } } if body == nil { + if c.Request.Body == nil { + return errors.New("cannot read nil body") + } body, err = io.ReadAll(c.Request.Body) if err != nil { return err diff --git a/context_test.go b/context_test.go index cef488c9..14b05c04 100644 --- a/context_test.go +++ b/context_test.go @@ -2748,6 +2748,15 @@ func TestContextShouldBindBodyWith(t *testing.T) { } } +func TestContextShouldBindBodyWithNilBody(t *testing.T) { + c, _ := CreateTestContext(httptest.NewRecorder()) + c.Request = &http.Request{} + + var obj struct{} + err := c.ShouldBindBodyWithJSON(&obj) + assert.EqualError(t, err, "cannot read nil body") +} + func TestContextShouldBindBodyWithJSON(t *testing.T) { for _, tt := range []struct { name string