Skip to content

Commit

Permalink
Add Conditions to Ensure Bind Succeeds with `Transfer-Encoding: chunk…
Browse files Browse the repository at this point in the history
…ed` (#2717)

* Add conditions to ensure Bind succeeds with `Transfer-Encoding: chunked`.

* Revert the ContentLength conditions for BindBody
  • Loading branch information
178inaba authored Dec 11, 2024
1 parent 3b01785 commit 0368ed8
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 2 deletions.
2 changes: 1 addition & 1 deletion bind.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ func (b *DefaultBinder) BindQueryParams(c Context, i interface{}) error {
// See MIMEMultipartForm: https://golang.org/pkg/net/http/#Request.ParseMultipartForm
func (b *DefaultBinder) BindBody(c Context, i interface{}) (err error) {
req := c.Request()
if req.ContentLength <= 0 {
if req.ContentLength == 0 {
return
}

Expand Down
26 changes: 25 additions & 1 deletion bind_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import (
"mime/multipart"
"net/http"
"net/http/httptest"
"net/http/httputil"
"net/url"
"reflect"
"strconv"
Expand Down Expand Up @@ -941,6 +942,7 @@ func TestDefaultBinder_BindBody(t *testing.T) {
givenMethod string
givenContentType string
whenNoPathParams bool
whenChunkedBody bool
whenBindTarget interface{}
expect interface{}
expectError string
Expand Down Expand Up @@ -1061,12 +1063,30 @@ func TestDefaultBinder_BindBody(t *testing.T) {
expectError: "code=415, message=Unsupported Media Type",
},
{
name: "ok, JSON POST bind to struct with: path + query + http.NoBody",
name: "nok, JSON POST with http.NoBody",
givenURL: "/api/real_node/endpoint?node=xxx",
givenMethod: http.MethodPost,
givenContentType: MIMEApplicationJSON,
givenContent: http.NoBody,
expect: &Node{ID: 0, Node: ""},
expectError: "code=400, message=EOF, internal=EOF",
},
{
name: "ok, JSON POST with empty body",
givenURL: "/api/real_node/endpoint?node=xxx",
givenMethod: http.MethodPost,
givenContentType: MIMEApplicationJSON,
givenContent: strings.NewReader(""),
expect: &Node{ID: 0, Node: ""},
},
{
name: "ok, JSON POST bind to struct with: path + query + chunked body",
givenURL: "/api/real_node/endpoint?node=xxx",
givenMethod: http.MethodPost,
givenContentType: MIMEApplicationJSON,
givenContent: httputil.NewChunkedReader(strings.NewReader("18\r\n" + `{"id": 1, "node": "zzz"}` + "\r\n0\r\n")),
whenChunkedBody: true,
expect: &Node{ID: 1, Node: "zzz"},
},
}

Expand All @@ -1083,6 +1103,10 @@ func TestDefaultBinder_BindBody(t *testing.T) {
case MIMEApplicationJSON:
req.Header.Set(HeaderContentType, MIMEApplicationJSON)
}
if tc.whenChunkedBody {
req.ContentLength = -1
req.TransferEncoding = append(req.TransferEncoding, "chunked")
}
rec := httptest.NewRecorder()
c := e.NewContext(req, rec)

Expand Down

0 comments on commit 0368ed8

Please sign in to comment.