Preserve request body in debug output for all methods#751
Preserve request body in debug output for all methods#751bkiran6398 wants to merge 2 commits intomainfrom
Conversation
- Enhanced the DebugTransport function to save and restore the request body for POST, PATCH, and PUT requests, ensuring the body is available for logging even after being consumed by the transport. - Added tests to verify that the request body is correctly logged in debug output for various HTTP methods, including error scenarios. - This change improves the debugging capabilities of the SDK by providing complete visibility into the requests being made.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #751 +/- ##
=======================================
Coverage 87.25% 87.25%
=======================================
Files 350 350
Lines 139272 139278 +6
=======================================
+ Hits 121519 121525 +6
Misses 13219 13219
Partials 4534 4534 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
developerkunal
left a comment
There was a problem hiding this comment.
A couple of small suggestions for the body-buffering block:
-
The original
req.Bodyis never explicitly closed afterReadAll. It would be good to callreq.Body.Close()before replacing it. -
The error from
io.ReadAllis silently discarded. If reading fails partway through, a truncated body would be sent to the server without the caller knowing. In practice this is unlikely since bodies are typicallybytes.Readerorstrings.Reader, but it's still worth handling.
Something like:
var bodyBytes []byte
if req.Body != nil {
bodyBytes, err := io.ReadAll(req.Body)
req.Body.Close()
if err != nil {
return nil, fmt.Errorf("debug transport: failed to read request body: %w", err)
}
req.Body = io.NopCloser(bytes.NewReader(bodyBytes))
}Otherwise the fix and tests look good!
- Cleaned up the DebugTransport function by removing an empty line.
🔧 Changes
Fixes
DebugTransportto preserve request bodies in debug log output for POST, PATCH, and PUT requests.Previously,
DebugTransportcalleddumpRequestafterbase.RoundTrip()to capture headers set by inner transports. However,RoundTripconsumes the request body stream, sohttputil.DumpRequestOutfound an empty body — making debug logs useless for any request with a payload.RoundTripand restores it afterward for dumping📚 References
🔬 Testing
Added 5 new unit tests to
TestDebugTransport:Run tests:
go test ./internal/client/ -run TestDebugTransport -v📝 Checklist