Skip to content

Commit

Permalink
Fix SetAllowGetMethodPayload option ignored for io.Reader payload (#541)
Browse files Browse the repository at this point in the history
Co-authored-by: Martin Picollo <martin.picollo@brubank.com>
  • Loading branch information
picollomartin and Martin Picollo committed Mar 6, 2023
1 parent 45d9f8b commit dc65180
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 11 deletions.
15 changes: 15 additions & 0 deletions client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -468,6 +468,21 @@ func TestClientAllowsGetMethodPayload(t *testing.T) {
assertEqual(t, payload, resp.String())
}

func TestClientAllowsGetMethodPayloadDisabled(t *testing.T) {
ts := createGetServer(t)
defer ts.Close()

c := dc()
c.SetAllowGetMethodPayload(false)

payload := bytes.NewReader([]byte("test-payload"))
resp, err := c.R().SetBody(payload).Get(ts.URL + "/get-method-payload-test")

assertError(t, err)
assertEqual(t, http.StatusOK, resp.StatusCode())
assertEqual(t, "", resp.String())
}

func TestClientRoundTripper(t *testing.T) {
c := NewWithClient(&http.Client{})
c.outputLogTo(ioutil.Discard)
Expand Down
15 changes: 4 additions & 11 deletions middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -164,9 +164,7 @@ CL:

func createHTTPRequest(c *Client, r *Request) (err error) {
if r.bodyBuf == nil {
if reader, ok := r.Body.(io.Reader); ok {
r.RawRequest, err = http.NewRequest(r.Method, r.URL, reader)
} else if c.setContentLength || r.setContentLength {
if c.setContentLength || r.setContentLength {
r.RawRequest, err = http.NewRequest(r.Method, r.URL, http.NoBody)
} else {
r.RawRequest, err = http.NewRequest(r.Method, r.URL, nil)
Expand Down Expand Up @@ -442,14 +440,9 @@ func handleRequestBody(c *Client, r *Request) (err error) {
r.bodyBuf = nil

if reader, ok := r.Body.(io.Reader); ok {
if c.setContentLength || r.setContentLength { // keep backward compatibility
r.bodyBuf = acquireBuffer()
_, err = r.bodyBuf.ReadFrom(reader)
r.Body = nil
} else {
// Otherwise buffer less processing for `io.Reader`, sounds good.
return
}
r.bodyBuf = acquireBuffer()
_, err = r.bodyBuf.ReadFrom(reader)
r.Body = nil
} else if b, ok := r.Body.([]byte); ok {
bodyBytes = b
} else if s, ok := r.Body.(string); ok {
Expand Down

0 comments on commit dc65180

Please sign in to comment.