diff --git a/context.go b/context.go index a6add8a6..d3a0ea2e 100644 --- a/context.go +++ b/context.go @@ -955,6 +955,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 b82e04d5..1bc216ac 100644 --- a/context_test.go +++ b/context_test.go @@ -2772,6 +2772,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