mirror of
https://github.com/gin-gonic/gin.git
synced 2026-01-14 02:56:58 +08:00
Merge cd9b91bb2ef67d3b409e8c2465c806a2d68f5178 into 9914178584e42458ff7d23891463a880f58c9d86
This commit is contained in:
commit
6af3929e47
@ -7,6 +7,7 @@ package binding
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
|
||||
@ -50,7 +51,12 @@ func decodeJSON(r io.Reader, obj any) error {
|
||||
decoder.DisallowUnknownFields()
|
||||
}
|
||||
if err := decoder.Decode(obj); err != nil {
|
||||
if errors.Is(err, io.EOF) {
|
||||
return fmt.Errorf("empty request body: %w", err)
|
||||
}
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
return validate(obj)
|
||||
}
|
||||
|
||||
39
binding/json_external_test.go
Normal file
39
binding/json_external_test.go
Normal file
@ -0,0 +1,39 @@
|
||||
package binding_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
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))
|
||||
require.NoError(t, err)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
c.Request = req
|
||||
|
||||
var r Req
|
||||
err = c.ShouldBindJSON(&r)
|
||||
|
||||
require.Error(t, err)
|
||||
|
||||
// Error message should be more descriptive than plain EOF,
|
||||
// while still preserving io.EOF via wrapping.
|
||||
assert.NotEqual(t, "EOF", err.Error())
|
||||
assert.Contains(t, err.Error(), "empty request body")
|
||||
assert.ErrorIs(t, err, io.EOF)
|
||||
}
|
||||
Loading…
x
Reference in New Issue
Block a user