Skip to content

Commit

Permalink
Address PR Comments
Browse files Browse the repository at this point in the history
  • Loading branch information
ezilber-akamai committed Jul 30, 2024
1 parent 7088c6c commit c8f692a
Show file tree
Hide file tree
Showing 2 changed files with 76 additions and 11 deletions.
53 changes: 50 additions & 3 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import (
"strconv"
"strings"
"sync"
"text/template"
"time"

"github.com/go-resty/resty/v2"
Expand Down Expand Up @@ -120,10 +121,15 @@ type RequestParams struct {

// Generic helper to execute HTTP requests using the
//
//nolint:unused
// noline: gocognit
//
// nolint:unused
// nolint:funlen
func (c *httpClient) doRequest(ctx context.Context, method, url string, params RequestParams, mutators ...func(req *http.Request) error) error {
// Create a new HTTP request
var bodyReader io.Reader
var bodyBuffer *bytes.Buffer

if params.Body != nil {
buf := new(bytes.Buffer)
if err := json.NewEncoder(buf).Encode(params.Body); err != nil {
Expand Down Expand Up @@ -162,7 +168,27 @@ func (c *httpClient) doRequest(ctx context.Context, method, url string, params R

// Log the request if in debug mode
if c.debug && c.logger != nil {
c.logger.Debugf("sending request: %s %s", method, url)
var reqBody string
if bodyBuffer != nil {
reqBody = bodyBuffer.String()
}

reqLog := `Sending request:
Method: {{.Method}}
URL: {{.URL}}
Headers: {{.Headers}}
Body: {{.Body}}`
tmpl, _ := template.New("request").Parse(reqLog)
var logBuf bytes.Buffer
err = tmpl.Execute(&logBuf, map[string]interface{}{
"Method": method,
"URL": url,
"Headers": req.Header,
"Body": reqBody,
})
if err == nil {
c.logger.Debugf(logBuf.String())
}
}

// Send the request
Expand All @@ -186,7 +212,28 @@ func (c *httpClient) doRequest(ctx context.Context, method, url string, params R

// Log the response if in debug mode
if c.debug && c.logger != nil {
c.logger.Debugf("received response: %s %s, status: %d", method, url, resp.StatusCode)
var respBody bytes.Buffer
if _, err := io.Copy(&respBody, resp.Body); err != nil {
c.logger.Errorf("failed to read response body: %v", err)
}

respLog := `Received response:
Status: {{.Status}}
Headers: {{.Headers}}
Body: {{.Body}}`
tmpl, _ := template.New("response").Parse(respLog)
var logBuf bytes.Buffer
err = tmpl.Execute(&logBuf, map[string]interface{}{
"Status": resp.Status,
"Headers": resp.Header,
"Body": respBody.String(),
})
if err == nil {
c.logger.Debugf(logBuf.String())
}

// Reset the response body reader for actual decoding
resp.Body = io.NopCloser(bytes.NewReader(respBody.Bytes()))
}

// Decode the response body
Expand Down
34 changes: 26 additions & 8 deletions client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -366,15 +366,17 @@ func TestDoRequestLogging_Success(t *testing.T) {
}

logInfo := logBuffer.String()
expectedLogs := []string{
"DEBUG RESTY sending request: GET " + server.URL,
"DEBUG RESTY received response: GET " + server.URL + ", status: 200",
}
logInfoWithoutTimestamps := removeTimestamps(logInfo)

for _, expectedLog := range expectedLogs {
if !strings.Contains(logInfo, expectedLog) {
t.Fatalf("expected log %q not found in logs", expectedLog)
}
// Expected logs with templates filled in
expectedRequestLog := "DEBUG RESTY Sending request:\nMethod: GET\nURL: " + server.URL + "\nHeaders: map[Accept:[application/json] Content-Type:[application/json]]\nBody: "
expectedResponseLog := "DEBUG RESTY Received response:\nStatus: 200 OK\nHeaders: map[Content-Length:[21] Content-Type:[text/plain; charset=utf-8]]\nBody: {\"message\":\"success\"}"

if !strings.Contains(logInfo, expectedRequestLog) {
t.Fatalf("expected log %q not found in logs", expectedRequestLog)
}
if !strings.Contains(logInfoWithoutTimestamps, expectedResponseLog) {
t.Fatalf("expected log %q not found in logs", expectedResponseLog)
}
}

Expand Down Expand Up @@ -408,3 +410,19 @@ func TestDoRequestLogging_Error(t *testing.T) {
t.Fatalf("expected log %q not found in logs", expectedLog)
}
}

func removeTimestamps(log string) string {
lines := strings.Split(log, "\n")
var filteredLines []string
for _, line := range lines {
// Find the index of the "Date:" substring
if index := strings.Index(line, "Date:"); index != -1 {
// Cut off everything after "Date:"
trimmedLine := strings.TrimSpace(line[:index])
filteredLines = append(filteredLines, trimmedLine+"]")
} else {
filteredLines = append(filteredLines, line)
}
}
return strings.Join(filteredLines, "\n")
}

0 comments on commit c8f692a

Please sign in to comment.