@@ -4,6 +4,7 @@ and unmarshals the response based on the content type (JSON or XML). */
44package response
55
66import (
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