diff --git a/bind.go b/bind.go index 2d0af0c7..c81484bf 100644 --- a/bind.go +++ b/bind.go @@ -42,6 +42,9 @@ func (b *DefaultBinder) Bind(i interface{}, c Context) (err error) { if err = b.bindPathData(i, c); err != nil { return NewHTTPError(http.StatusBadRequest, err.Error()) } + if err = b.bindPathData(i, c); err != nil { + return NewHTTPError(http.StatusBadRequest, err.Error()) + } ctype := req.Header.Get(HeaderContentType) switch { case strings.HasPrefix(ctype, MIMEApplicationJSON): @@ -79,7 +82,10 @@ func (b *DefaultBinder) Bind(i interface{}, c Context) (err error) { } func (b *DefaultBinder) bindPathData(ptr interface{}, c Context) error { - m := make(map[string][]string) + if reflect.TypeOf(ptr).Elem().Kind() == reflect.Slice { + return nil + } + m := make(map[string][]string, len(c.ParamNames())) for _, key := range c.ParamNames() { m[key] = []string{c.Param(key)} } diff --git a/bind_test.go b/bind_test.go index cc7889e2..69ccc5d0 100644 --- a/bind_test.go +++ b/bind_test.go @@ -118,6 +118,7 @@ var values = map[string][]string{ func TestBindJSON(t *testing.T) { testBindOkay(t, strings.NewReader(userJSON), MIMEApplicationJSON) testBindError(t, strings.NewReader(invalidContent), MIMEApplicationJSON) + testBindSlice(t, strings.NewReader(userJSONArray), MIMEApplicationJSON) } func TestBindXML(t *testing.T) { @@ -349,3 +350,19 @@ func testBindError(t *testing.T, r io.Reader, ctype string) { } } } + +func testBindSlice(t *testing.T, r io.Reader, ctype string) { + e := New() + req := httptest.NewRequest(POST, "/", r) + rec := httptest.NewRecorder() + c := e.NewContext(req, rec) + req.Header.Set(HeaderContentType, ctype) + us := []user{} + err := c.Bind(&us) + if assert.NoError(t, err) { + assert.Equal(t, 1, us[0].ID) + assert.Equal(t, "Jon Snow", us[0].Name) + assert.Equal(t, 2, us[1].ID) + assert.Equal(t, "Arya Stark", us[1].Name) + } +} diff --git a/echo_test.go b/echo_test.go index e38d7c09..96e62720 100644 --- a/echo_test.go +++ b/echo_test.go @@ -25,6 +25,7 @@ type ( const ( userJSON = `{"id":1,"name":"Jon Snow"}` + userJSONArray = `[{"id":1,"name":"Jon Snow"},{"id":2,"name":"Arya Stark"}]` userJSONOnlyName = `{"name":"Jon Snow"}` userXML = `1Jon Snow` userForm = `id=1&name=Jon Snow`