Response Body in Logger is always empty #98
-
I paste here an example code to reproduce the issue: logger := func(_ *http.Request, res *http.Response, _ error, _ time.Duration) {
result, err := io.ReadAll(res.Body)
log.Println("Body Length", len(result))
log.Println("Body", result)
log.Println("Body error", err)
}
// Wrap an existing transport or use nil for http.DefaultTransport
baseTrans := http.DefaultClient.Transport
trans := requests.LogTransport(baseTrans, logger)
var result any
// A random JSON API
err := requests.URL("https://worldtimeapi.org/api/timezone").
Transport(trans).
ToJSON(&result).
Fetch(context.Background())
log.Println("Result", result)
log.Println("Request Error", err) The I would suggest to add more tests in this part of code after fixing the problem. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
The response body is an io.ReadCloser, so it can't be read by both ToJSON and the logger. It needs to be one or the other. Once you read from a reader, it's gone. You can work around that by various means (save to a string and then use the string for logging and JSON or use some other kind of replayable buffer), but it's sort of a fundamental part of how io.Reader works that to save memory by default it won't "rewind". |
Beta Was this translation helpful? Give feedback.
No, the logger transport is triggered last. That's how it knows what the request duration is.