@@ -4,6 +4,7 @@ and unmarshals the response based on the content type (JSON or XML). */
4
4
package response
5
5
6
6
import (
7
+ "bytes"
7
8
"encoding/json"
8
9
"encoding/xml"
9
10
"errors"
@@ -32,18 +33,26 @@ func HandleAPISuccessResponse(resp *http.Response, out interface{}, log logger.L
32
33
return handleDeleteRequest (resp , log )
33
34
}
34
35
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 )
37
44
38
45
mimeType , _ := ParseContentTypeHeader (resp .Header .Get ("Content-Type" ))
39
46
contentDisposition := resp .Header .Get ("Content-Disposition" )
40
47
41
48
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
44
52
} 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
47
56
} else {
48
57
errMsg := fmt .Sprintf ("unexpected MIME type: %s" , mimeType )
49
58
log .Error ("Unmarshal error" , zap .String ("content type" , mimeType ), zap .Error (errors .New (errMsg )))
0 commit comments