From daabe58f889ce76d3a82a9d234a32d881819401f Mon Sep 17 00:00:00 2001 From: Penny Date: Mon, 19 Aug 2024 19:24:58 +0800 Subject: [PATCH] fix: Log request body (#272) --- client.go | 33 ++++++++++++--------------------- 1 file changed, 12 insertions(+), 21 deletions(-) diff --git a/client.go b/client.go index 2c78739..5ead6e1 100644 --- a/client.go +++ b/client.go @@ -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) @@ -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)))) - } -}