Skip to content

Commit 97187c4

Browse files
authored
Fixed JSONIndent request logging data race. (#775)
1 parent bf77da8 commit 97187c4

File tree

2 files changed

+32
-5
lines changed

2 files changed

+32
-5
lines changed

client_test.go

+23
Original file line numberDiff line numberDiff line change
@@ -766,6 +766,29 @@ func TestLogCallbacks(t *testing.T) {
766766
assertNotNil(t, resp)
767767
}
768768

769+
func TestDebugLogSimultaneously(t *testing.T) {
770+
ts := createGetServer(t)
771+
772+
c := New().
773+
SetDebug(true).
774+
SetBaseURL(ts.URL).
775+
outputLogTo(io.Discard)
776+
777+
t.Cleanup(ts.Close)
778+
for i := 0; i < 50; i++ {
779+
t.Run(fmt.Sprint(i), func(t *testing.T) {
780+
t.Parallel()
781+
resp, err := c.R().
782+
SetBody([]int{1, 2, 3}).
783+
SetHeader(hdrContentTypeKey, "application/json; charset=utf-8").
784+
Post("/")
785+
786+
assertError(t, err)
787+
assertEqual(t, http.StatusOK, resp.StatusCode())
788+
})
789+
}
790+
}
791+
769792
func TestNewWithLocalAddr(t *testing.T) {
770793
ts := createGetServer(t)
771794
defer ts.Close()

request.go

+9-5
Original file line numberDiff line numberDiff line change
@@ -1014,7 +1014,12 @@ func (r *Request) fmtBodyString(sl int64) (body string) {
10141014
contentType := r.Header.Get(hdrContentTypeKey)
10151015
kind := kindOf(r.Body)
10161016
if canJSONMarshal(contentType, kind) {
1017-
prtBodyBytes, err = noescapeJSONMarshalIndent(&r.Body)
1017+
var bodyBuf *bytes.Buffer
1018+
bodyBuf, err = noescapeJSONMarshalIndent(&r.Body)
1019+
if err == nil {
1020+
prtBodyBytes = bodyBuf.Bytes()
1021+
defer releaseBuffer(bodyBuf)
1022+
}
10181023
} else if IsXMLType(contentType) && (kind == reflect.Struct) {
10191024
prtBodyBytes, err = xml.MarshalIndent(&r.Body, "", " ")
10201025
} else if b, ok := r.Body.(string); ok {
@@ -1077,17 +1082,16 @@ var noescapeJSONMarshal = func(v interface{}) (*bytes.Buffer, error) {
10771082
return buf, nil
10781083
}
10791084

1080-
var noescapeJSONMarshalIndent = func(v interface{}) ([]byte, error) {
1085+
var noescapeJSONMarshalIndent = func(v interface{}) (*bytes.Buffer, error) {
10811086
buf := acquireBuffer()
1082-
defer releaseBuffer(buf)
1083-
10841087
encoder := json.NewEncoder(buf)
10851088
encoder.SetEscapeHTML(false)
10861089
encoder.SetIndent("", " ")
10871090

10881091
if err := encoder.Encode(v); err != nil {
1092+
releaseBuffer(buf)
10891093
return nil, err
10901094
}
10911095

1092-
return buf.Bytes(), nil
1096+
return buf, nil
10931097
}

0 commit comments

Comments
 (0)