Improve BindJSON by avoiding panic when request.Body is nil

This commit is contained in:
Focinfi 2016-04-22 09:27:24 +08:00
parent 542be2fe77
commit 2fb4bb2bda
2 changed files with 21 additions and 0 deletions

View File

@ -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

View File

@ -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\"}"))