diff --git a/binding/json.go b/binding/json.go index 6e532443..7f3e2d39 100644 --- a/binding/json.go +++ b/binding/json.go @@ -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 diff --git a/context_test.go b/context_test.go index 97d4957c..cb35950d 100644 --- a/context_test.go +++ b/context_test.go @@ -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\"}"))