diff --git a/middleware.go b/middleware.go index 64573d0d..a0ba0700 100644 --- a/middleware.go +++ b/middleware.go @@ -196,6 +196,10 @@ func parseRequestBody(c *Client, r *Request) error { } case len(c.FormData) > 0 || len(r.FormData) > 0: // Handling Form Data handleFormData(c, r) + case r.Body == nil && r.bodyBuf == nil: // Handling Request body when nil body + // Go http library omits Content-Length if body is nil; use http.NoBody to force it if SetContentLength is true + r.Body = http.NoBody + fallthrough case r.Body != nil: // Handling Request body handleContentType(c, r) @@ -315,6 +319,7 @@ func createCurlCmd(c *Client, r *Request) (err error) { } *r.resultCurlCmd = buildCurlRequest(r.RawRequest, c.httpClient.Jar) } + return nil } diff --git a/middleware_test.go b/middleware_test.go index d85514e6..b4c57db8 100644 --- a/middleware_test.go +++ b/middleware_test.go @@ -513,6 +513,7 @@ func Test_parseRequestBody(t *testing.T) { r.SetContentLength(true) }, expectedContentLength: "0", + expectedBodyBuf: []byte{}, }, { name: "empty body with SetContentLength by client", @@ -520,6 +521,7 @@ func Test_parseRequestBody(t *testing.T) { c.SetContentLength(true) }, expectedContentLength: "0", + expectedBodyBuf: []byte{}, }, { name: "string body", diff --git a/request_test.go b/request_test.go index 00127d33..0d61e666 100644 --- a/request_test.go +++ b/request_test.go @@ -2283,3 +2283,27 @@ func TestRequestGH917(t *testing.T) { } wg.Wait() } + +func TestSetContentLengthTrueWithNilBody(t *testing.T) { + ts := createPostServer(t) + defer ts.Close() + + c := dc() + + c.OnBeforeRequest(func(client *Client, request *Request) error { + request. + SetBody(nil). + SetContentLength(true) + + return nil + }) + + c = c.SetBaseURL(ts.URL) + + resp, err := c.R().Execute("POST", "/check-request-content-length") + + assertNil(t, err) + + // when body is nil and SetContentLength is true expect Content-Length == "0" + assertEqual(t, "0", resp.Header().Get("Request-Content-Length")) +} diff --git a/resty_test.go b/resty_test.go index 7637c4bb..2df4176a 100644 --- a/resty_test.go +++ b/resty_test.go @@ -326,6 +326,10 @@ func createPostServer(t *testing.T) *httptest.Server { } http.SetCookie(w, &cookie) w.WriteHeader(http.StatusOK) + case "/check-request-content-length": + // test endpoint for checking the server receives the correct Content-Length Header from a request + w.Header().Add("Request-Content-Length", r.Header.Get("Content-Length")) + w.WriteHeader(http.StatusOK) } } })