fix(context): handle nil request body in ShouldBindBodyWith

Fixes #1973
This commit is contained in:
sb123sb123 2026-09-22 13:03:46 +08:00
parent 3b08cd7235
commit f6c0ff96d8
2 changed files with 12 additions and 0 deletions

View File

@ -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

View File

@ -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