mirror of
https://github.com/gin-gonic/gin.git
synced 2025-10-15 13:02:14 +08:00
Improve BindJSON by avoiding panic when request.Body is nil
This commit is contained in:
parent
542be2fe77
commit
2fb4bb2bda
@ -6,6 +6,7 @@ package binding
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
|
||||
"net/http"
|
||||
)
|
||||
@ -17,6 +18,10 @@ func (jsonBinding) Name() string {
|
||||
}
|
||||
|
||||
func (jsonBinding) Bind(req *http.Request, obj interface{}) error {
|
||||
if req.Body == nil {
|
||||
return errors.New("can not bind a request with a nil body")
|
||||
}
|
||||
|
||||
decoder := json.NewDecoder(req.Body)
|
||||
if err := decoder.Decode(obj); err != nil {
|
||||
return err
|
||||
|
@ -670,6 +670,22 @@ func TestContextBindWithJSON(t *testing.T) {
|
||||
assert.Equal(t, w.Body.Len(), 0)
|
||||
}
|
||||
|
||||
func TestContextBindWithNilBody(t *testing.T) {
|
||||
c, _, _ := CreateTestContext()
|
||||
c.Request, _ = http.NewRequest("POST", "/", nil)
|
||||
c.Request.Header.Add("Content-Type", MIMEXML) // set fake content-type
|
||||
|
||||
var obj struct {
|
||||
Foo string `json:"foo"`
|
||||
Bar string `json:"bar"`
|
||||
}
|
||||
|
||||
assert.Error(t, c.BindJSON(&obj))
|
||||
assert.NotPanics(t, func() {
|
||||
c.BindJSON(&obj)
|
||||
})
|
||||
}
|
||||
|
||||
func TestContextBadAutoBind(t *testing.T) {
|
||||
c, w, _ := CreateTestContext()
|
||||
c.Request, _ = http.NewRequest("POST", "http://example.com", bytes.NewBufferString("\"foo\":\"bar\", \"bar\":\"foo\"}"))
|
||||
|
Loading…
x
Reference in New Issue
Block a user