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