Skip to content

Commit

Permalink
log response bodies when debug is enabled
Browse files Browse the repository at this point in the history
  • Loading branch information
michaeldwan committed May 19, 2021
1 parent 9f2b164 commit e6f290f
Showing 1 changed file with 11 additions and 2 deletions.
13 changes: 11 additions & 2 deletions api/http.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
package api

import (
"bytes"
"context"
"io"
"net/http"
"strings"
"time"
Expand Down Expand Up @@ -83,9 +85,16 @@ func (t *LoggingTransport) logRequest(req *http.Request) {

func (t *LoggingTransport) logResponse(resp *http.Response) {
ctx := resp.Request.Context()
defer resp.Body.Close()
data, err := io.ReadAll(resp.Body)
if err != nil {
terminal.Debug("error reading response body:", err)
}
if start, ok := ctx.Value(contextKeyRequestStart).(time.Time); ok {
terminal.Debugf("<-- %d %s (%s)\n", resp.StatusCode, resp.Request.URL, helpers.Duration(time.Now().Sub(start), 2))
terminal.Debugf("<-- %d %s (%s) %s\n", resp.StatusCode, resp.Request.URL, helpers.Duration(time.Since(start), 2), string(data))
} else {
terminal.Debugf("<-- %d %s\n", resp.StatusCode, resp.Request.URL)
terminal.Debugf("<-- %d %s %s %s\n", resp.StatusCode, resp.Request.URL, string(data))
}

resp.Body = io.NopCloser(bytes.NewReader(data))
}

0 comments on commit e6f290f

Please sign in to comment.