Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Conditions to Ensure Bind Succeeds with Transfer-Encoding: chunked #2717

Merged
merged 2 commits into from
Dec 11, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion bind.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,14 @@ 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 {
aldas marked this conversation as resolved.
Show resolved Hide resolved
var isChunked bool
for _, enc := range req.TransferEncoding {
if enc == "chunked" {
isChunked = true
break
}
}
if req.ContentLength <= 0 && !isChunked {
return
}

Expand Down
15 changes: 15 additions & 0 deletions 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 @@ -1068,6 +1070,15 @@ func TestDefaultBinder_BindBody(t *testing.T) {
givenContent: http.NoBody,
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"},
},
}

for _, tc := range testCases {
Expand All @@ -1083,6 +1094,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
Loading