Skip to content

Commit

Permalink
fix: Log request body (#272)
Browse files Browse the repository at this point in the history
  • Loading branch information
spyth authored Aug 19, 2024
1 parent 5052fd4 commit daabe58
Showing 1 changed file with 12 additions and 21 deletions.
33 changes: 12 additions & 21 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -97,13 +97,23 @@ func (c *Client) Send(req *http.Request, v interface{}) error {
if c.returnRepresentation {
req.Header.Set("Prefer", "return=representation")
}
if c.Log != nil {
if reqDump, err := httputil.DumpRequestOut(req, true); err == nil {
c.Log.Write([]byte(fmt.Sprintf("Request: %s\n", reqDump)))
}
}

resp, err = c.Client.Do(req)
c.log(req, resp)

if err != nil {
return err
}

if c.Log != nil {
if respDump, err := httputil.DumpResponse(resp, true); err == nil {
c.Log.Write([]byte(fmt.Sprintf("Response from %s: %s\n", req.URL, respDump)))
}
}

defer func(Body io.ReadCloser) error {
return Body.Close()
}(resp.Body)
Expand Down Expand Up @@ -180,22 +190,3 @@ func (c *Client) NewRequest(ctx context.Context, method, url string, payload int
}
return http.NewRequestWithContext(ctx, method, url, buf)
}

// log will dump request and response to the log file
func (c *Client) log(r *http.Request, resp *http.Response) {
if c.Log != nil {
var (
reqDump string
respDump []byte
)

if r != nil {
reqDump = fmt.Sprintf("%s %s. Data: %s", r.Method, r.URL.String(), r.Form.Encode())
}
if resp != nil {
respDump, _ = httputil.DumpResponse(resp, true)
}

c.Log.Write([]byte(fmt.Sprintf("Request: %s\nResponse: %s\n", reqDump, string(respDump))))
}
}

0 comments on commit daabe58

Please sign in to comment.