Skip to content

Commit

Permalink
Fixed JSONIndent request logging data race. (#775)
Browse files Browse the repository at this point in the history
  • Loading branch information
buglloc committed Feb 19, 2024
1 parent bf77da8 commit 97187c4
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 5 deletions.
23 changes: 23 additions & 0 deletions client_test.go
Expand Up @@ -766,6 +766,29 @@ func TestLogCallbacks(t *testing.T) {
assertNotNil(t, resp)
}

func TestDebugLogSimultaneously(t *testing.T) {
ts := createGetServer(t)

c := New().
SetDebug(true).
SetBaseURL(ts.URL).
outputLogTo(io.Discard)

t.Cleanup(ts.Close)
for i := 0; i < 50; i++ {
t.Run(fmt.Sprint(i), func(t *testing.T) {
t.Parallel()
resp, err := c.R().
SetBody([]int{1, 2, 3}).
SetHeader(hdrContentTypeKey, "application/json; charset=utf-8").
Post("/")

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

func TestNewWithLocalAddr(t *testing.T) {
ts := createGetServer(t)
defer ts.Close()
Expand Down
14 changes: 9 additions & 5 deletions request.go
Expand Up @@ -1014,7 +1014,12 @@ func (r *Request) fmtBodyString(sl int64) (body string) {
contentType := r.Header.Get(hdrContentTypeKey)
kind := kindOf(r.Body)
if canJSONMarshal(contentType, kind) {
prtBodyBytes, err = noescapeJSONMarshalIndent(&r.Body)
var bodyBuf *bytes.Buffer
bodyBuf, err = noescapeJSONMarshalIndent(&r.Body)
if err == nil {
prtBodyBytes = bodyBuf.Bytes()
defer releaseBuffer(bodyBuf)
}
} else if IsXMLType(contentType) && (kind == reflect.Struct) {
prtBodyBytes, err = xml.MarshalIndent(&r.Body, "", " ")
} else if b, ok := r.Body.(string); ok {
Expand Down Expand Up @@ -1077,17 +1082,16 @@ var noescapeJSONMarshal = func(v interface{}) (*bytes.Buffer, error) {
return buf, nil
}

var noescapeJSONMarshalIndent = func(v interface{}) ([]byte, error) {
var noescapeJSONMarshalIndent = func(v interface{}) (*bytes.Buffer, error) {
buf := acquireBuffer()
defer releaseBuffer(buf)

encoder := json.NewEncoder(buf)
encoder.SetEscapeHTML(false)
encoder.SetIndent("", " ")

if err := encoder.Encode(v); err != nil {
releaseBuffer(buf)
return nil, err
}

return buf.Bytes(), nil
return buf, nil
}

0 comments on commit 97187c4

Please sign in to comment.