mirror of
https://github.com/gin-gonic/gin.git
synced 2026-06-05 10:28:21 +08:00
Wrap EOF with helpful message for empty JSON request body
This commit is contained in:
parent
9914178584
commit
4a81d5807a
@ -7,6 +7,7 @@ package binding
|
|||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
"errors"
|
"errors"
|
||||||
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
@ -50,7 +51,11 @@ func decodeJSON(r io.Reader, obj any) error {
|
|||||||
decoder.DisallowUnknownFields()
|
decoder.DisallowUnknownFields()
|
||||||
}
|
}
|
||||||
if err := decoder.Decode(obj); err != nil {
|
if err := decoder.Decode(obj); err != nil {
|
||||||
|
if err == io.EOF {
|
||||||
|
return fmt.Errorf("empty request body: %w", err)
|
||||||
|
}
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
return validate(obj)
|
return validate(obj)
|
||||||
}
|
}
|
||||||
|
|||||||
38
binding/json_external_test.go
Normal file
38
binding/json_external_test.go
Normal file
@ -0,0 +1,38 @@
|
|||||||
|
package binding_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestJSONBindingEmptyBodyReturnsHelpfulError(t *testing.T) {
|
||||||
|
type Req struct {
|
||||||
|
Name string `json:"name" binding:"required"`
|
||||||
|
}
|
||||||
|
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
c, _ := gin.CreateTestContext(w)
|
||||||
|
|
||||||
|
req, err := http.NewRequest(http.MethodPost, "/", bytes.NewBuffer(nil))
|
||||||
|
assert.NoError(t, err)
|
||||||
|
req.Header.Set("Content-Type", "application/json")
|
||||||
|
|
||||||
|
c.Request = req
|
||||||
|
|
||||||
|
var r Req
|
||||||
|
err = c.ShouldBindJSON(&r)
|
||||||
|
|
||||||
|
assert.Error(t, err)
|
||||||
|
|
||||||
|
// Current behavior returns plain "EOF", which is not helpful.
|
||||||
|
assert.NotEqual(t, "EOF", err.Error(), "error message should not be plain EOF")
|
||||||
|
assert.Contains(t, err.Error(), "empty request body")
|
||||||
|
assert.ErrorIs(t, err, io.EOF)
|
||||||
|
|
||||||
|
}
|
||||||
Loading…
x
Reference in New Issue
Block a user