mirror of
https://github.com/gin-gonic/gin.git
synced 2025-10-14 04:08:15 +08:00
Merge 67d4ff8f6e6da871511bd2815edadcaa5c8f7b7f into c3d1092b3b48addf6f9cd00fe274ec3bd14650eb
This commit is contained in:
commit
75f18af152
16
context.go
16
context.go
@ -5,6 +5,7 @@
|
||||
package gin
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
@ -739,6 +740,21 @@ func (c *Context) Bind(obj any) error {
|
||||
|
||||
// BindJSON is a shortcut for c.MustBindWith(obj, binding.JSON).
|
||||
func (c *Context) BindJSON(obj any) error {
|
||||
|
||||
body, err := io.ReadAll(c.Request.Body)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to read body: %v", err)
|
||||
}
|
||||
|
||||
// If the body is empty, set it to {}
|
||||
if len(body) == 0 {
|
||||
body = []byte("{}")
|
||||
c.Request.Body = io.NopCloser(bytes.NewBuffer(body)) // Set to {} to trigger the error
|
||||
return c.MustBindWith(obj, binding.JSON)
|
||||
}
|
||||
|
||||
// Restore the body since it was read
|
||||
c.Request.Body = io.NopCloser(bytes.NewBuffer(body))
|
||||
return c.MustBindWith(obj, binding.JSON)
|
||||
}
|
||||
|
||||
|
Loading…
x
Reference in New Issue
Block a user