feat: BindJSON Unfriendly prompt when parsing empty body.

This commit is contained in:
toad 2024-12-27 16:37:01 +08:00
parent 3f818c3fa6
commit 924e4f49a0
2 changed files with 12 additions and 0 deletions

View File

@ -50,6 +50,9 @@ 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 errors.New("empty body")
}
return err return err
} }
return validate(obj) return validate(obj)

View File

@ -5,6 +5,7 @@
package binding package binding
import ( import (
"strings"
"testing" "testing"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
@ -28,3 +29,11 @@ func TestJSONBindingBindBodyMap(t *testing.T) {
assert.Equal(t, "FOO", s["foo"]) assert.Equal(t, "FOO", s["foo"])
assert.Equal(t, "world", s["hello"]) assert.Equal(t, "world", s["hello"])
} }
func TestJSONBindingBindEmpty(t *testing.T) {
var s struct {
Foo string `binding:"required"`
}
err := jsonBinding{}.BindBody([]byte(""), &s)
require.True(t, strings.Contains(err.Error(), "empty body"))
}