Skip to content

Commit

Permalink
Set ContentLength=0 when body is nil and setContentLength is true (#698)
Browse files Browse the repository at this point in the history
  • Loading branch information
praem90 committed Sep 22, 2023
1 parent 1969424 commit 9ef9b6f
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 2 deletions.
11 changes: 11 additions & 0 deletions client_test.go
Expand Up @@ -488,6 +488,17 @@ func TestClientOptions(t *testing.T) {
assertEqual(t, client.closeConnection, true)
}

func TestContentLengthWhenBodyIsNil(t *testing.T) {
client := dc()

client.SetPreRequestHook(func(c *Client, r *http.Request) error {
assertEqual(t, "0", r.Header.Get(hdrContentLengthKey))
return nil
})

client.R().SetContentLength(true).SetBody(nil).Get("http://localhost")
}

func TestClientPreRequestHook(t *testing.T) {
client := dc()
client.SetPreRequestHook(func(c *Client, r *http.Request) error {
Expand Down
8 changes: 6 additions & 2 deletions middleware.go
Expand Up @@ -166,8 +166,12 @@ func parseRequestBody(c *Client, r *Request) (err error) {

CL:
// by default resty won't set content length, you can if you want to :)
if (c.setContentLength || r.setContentLength) && r.bodyBuf != nil {
r.Header.Set(hdrContentLengthKey, fmt.Sprintf("%d", r.bodyBuf.Len()))
if c.setContentLength || r.setContentLength {
if r.bodyBuf == nil {
r.Header.Set(hdrContentLengthKey, "0")
} else {
r.Header.Set(hdrContentLengthKey, fmt.Sprintf("%d", r.bodyBuf.Len()))
}
}

return
Expand Down

0 comments on commit 9ef9b6f

Please sign in to comment.