Skip to content

Commit 67cf80b

Browse files
committed
fix: buffer reset issue in io.Reader with content length enabled #917
1 parent feedf18 commit 67cf80b

File tree

2 files changed

+46
-2
lines changed

2 files changed

+46
-2
lines changed

request_test.go

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,11 +12,13 @@ import (
1212
"io"
1313
"net"
1414
"net/http"
15+
"net/http/httptest"
1516
"net/url"
1617
"os"
1718
"path/filepath"
1819
"strconv"
1920
"strings"
21+
"sync"
2022
"testing"
2123
"time"
2224

@@ -2195,3 +2197,40 @@ func TestSetResultMustNotPanicOnNil(t *testing.T) {
21952197
}()
21962198
dc().R().SetResult(nil)
21972199
}
2200+
2201+
func TestRequestGH917(t *testing.T) {
2202+
// Mock server returns 500 status code to cause client retries.
2203+
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
2204+
b, err := io.ReadAll(r.Body)
2205+
assertError(t, err)
2206+
if len(b) > 0 {
2207+
// sometimes, the body is "testtest" instead of "test"
2208+
assertEqual(t, "test", string(b))
2209+
}
2210+
w.WriteHeader(http.StatusInternalServerError)
2211+
}))
2212+
2213+
client := New().AddRetryCondition(
2214+
func(r *Response, err error) bool {
2215+
return err != nil || r.StatusCode() > 499
2216+
},
2217+
).SetRetryCount(3)
2218+
2219+
wg := sync.WaitGroup{}
2220+
// Run tests concurrently to make the issue easily to observe.
2221+
for i := 0; i < 100; i++ {
2222+
wg.Add(1)
2223+
go func() {
2224+
defer wg.Done()
2225+
for j := 0; j < 10; j++ {
2226+
buf := bytes.NewBufferString("test")
2227+
// Trigger some retries
2228+
resp, err := client.R().SetBody(buf).SetContentLength(true).Execute(http.MethodPost, srv.URL)
2229+
assertNil(t, err)
2230+
assertEqual(t, http.StatusInternalServerError, resp.StatusCode())
2231+
assertEqual(t, "", string(resp.Body()))
2232+
}
2233+
}()
2234+
}
2235+
wg.Wait()
2236+
}

util.go

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -286,12 +286,17 @@ func functionName(i interface{}) string {
286286
}
287287

288288
func acquireBuffer() *bytes.Buffer {
289-
return bufPool.Get().(*bytes.Buffer)
289+
buf := bufPool.Get().(*bytes.Buffer)
290+
if buf.Len() == 0 {
291+
buf.Reset()
292+
return buf
293+
}
294+
bufPool.Put(buf)
295+
return new(bytes.Buffer)
290296
}
291297

292298
func releaseBuffer(buf *bytes.Buffer) {
293299
if buf != nil {
294-
buf.Reset()
295300
bufPool.Put(buf)
296301
}
297302
}

0 commit comments

Comments
 (0)