Skip to content

Commit c6c4c89

Browse files
committed
Refactor response/success.go to read and log the response body
1 parent 07c3e66 commit c6c4c89

File tree

1 file changed

+15
-6
lines changed

1 file changed

+15
-6
lines changed

response/success.go

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ and unmarshals the response based on the content type (JSON or XML). */
44
package response
55

66
import (
7+
"bytes"
78
"encoding/json"
89
"encoding/xml"
910
"errors"
@@ -32,18 +33,26 @@ func HandleAPISuccessResponse(resp *http.Response, out interface{}, log logger.L
3233
return handleDeleteRequest(resp, log)
3334
}
3435

35-
// No need to read the entire body into memory, pass resp.Body directly.
36-
logResponseDetails(resp, nil, log) // Updated to handle nil bodyBytes.
36+
// Create a buffer to hold a copy of the response body
37+
var bodyBuffer bytes.Buffer
38+
39+
// Use TeeReader to read the response body and simultaneously write it to the buffer
40+
teeReader := io.TeeReader(resp.Body, &bodyBuffer)
41+
42+
// log the response body
43+
logResponseDetails(resp, bodyBuffer.Bytes(), log)
3744

3845
mimeType, _ := ParseContentTypeHeader(resp.Header.Get("Content-Type"))
3946
contentDisposition := resp.Header.Get("Content-Disposition")
4047

4148
if handler, ok := responseUnmarshallers[mimeType]; ok {
42-
// Pass resp.Body directly to the handler for streaming.
43-
return handler(resp.Body, out, log, mimeType)
49+
// Replace the response body with a new reader that reads from the buffer, allowing it to be read again
50+
resp.Body = io.NopCloser(&bodyBuffer)
51+
return handler(teeReader, out, log, mimeType) // Use teeReader here to unmarshal from the original response body
4452
} else if isBinaryData(mimeType, contentDisposition) {
45-
// For binary data, we still need to handle the body directly.
46-
return handleBinaryData(resp.Body, log, out, mimeType, contentDisposition)
53+
// Replace the response body with a new reader that reads from the buffer, allowing it to be read again
54+
resp.Body = io.NopCloser(&bodyBuffer)
55+
return handleBinaryData(teeReader, log, out, mimeType, contentDisposition) // Use teeReader here to handle binary data
4756
} else {
4857
errMsg := fmt.Sprintf("unexpected MIME type: %s", mimeType)
4958
log.Error("Unmarshal error", zap.String("content type", mimeType), zap.Error(errors.New(errMsg)))

0 commit comments

Comments
 (0)