Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixed JSON request logging data race. #775

Merged
merged 1 commit into from Feb 19, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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 @@
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 @@
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)

Check warning on line 1092 in request.go

View check run for this annotation

Codecov / codecov/patch

request.go#L1092

Added line #L1092 was not covered by tests
return nil, err
}

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