Skip to content

Commit

Permalink
feat: BindJSON Unfriendly prompt when parsing empty body.
Browse files Browse the repository at this point in the history
  • Loading branch information
tttoad committed Dec 27, 2024
1 parent e46bd52 commit 6870a3e
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 0 deletions.
3 changes: 3 additions & 0 deletions binding/json.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,9 @@ func decodeJSON(r io.Reader, obj any) error {
decoder.DisallowUnknownFields()
}
if err := decoder.Decode(obj); err != nil {
if err == io.EOF {
return errors.New("empty body")
}
return err
}
return validate(obj)
Expand Down
9 changes: 9 additions & 0 deletions binding/json_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
package binding

import (
"strings"
"testing"

"github.com/stretchr/testify/assert"
Expand All @@ -28,3 +29,11 @@ func TestJSONBindingBindBodyMap(t *testing.T) {
assert.Equal(t, "FOO", s["foo"])
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"))
}

0 comments on commit 6870a3e

Please sign in to comment.