Skip to content

Commit

Permalink
Debug for requests
Browse files Browse the repository at this point in the history
  • Loading branch information
Mike Zarechenskyi committed Jul 10, 2024
1 parent ca039a4 commit cf76690
Showing 1 changed file with 65 additions and 1 deletion.
66 changes: 65 additions & 1 deletion ah/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import (
"io"
"net/http"
"net/url"
"strings"
)

var (
Expand Down Expand Up @@ -115,8 +116,11 @@ func (c *APIClient) list(ctx context.Context, path string, options *ListOptions,
// Do sends an API request
func (c *APIClient) Do(ctx context.Context, req *http.Request, v interface{}) (*http.Response, error) {
req = req.WithContext(ctx)
resp, err := c.client.Do(req)

// Log the request details
c.logRequest(req)

resp, err := c.client.Do(req)
if err != nil {
return nil, err
}
Expand All @@ -143,7 +147,67 @@ func (c *APIClient) Do(ctx context.Context, req *http.Request, v interface{}) (*
return nil, err
}
return resp, nil
}

func (c *APIClient) logRequest(req *http.Request) {
// Log the request method and URL
fmt.Printf("Request: %s %s\n", req.Method, req.URL.String())

// Log the request headers
fmt.Println("Headers:")
for name, values := range req.Header {
for _, value := range values {
fmt.Printf("%s: %s\n", name, value)
}
}

// Log the request body if present
if req.Body != nil {
var bodyBytes []byte
if req.Body != nil {
bodyBytes, _ = io.ReadAll(req.Body)
req.Body = io.NopCloser(bytes.NewBuffer(bodyBytes))
}
if len(bodyBytes) > 0 {
fmt.Printf("Body: %s\n", string(bodyBytes))
}
}

// Generate and log the curl command
curlCommand := c.generateCurlCommand(req)
fmt.Printf("Curl: %s\n", curlCommand)
}

func (c *APIClient) generateCurlCommand(req *http.Request) string {
var curlCommand strings.Builder

curlCommand.WriteString("curl -X ")
curlCommand.WriteString(req.Method)
curlCommand.WriteString(" '")
curlCommand.WriteString(req.URL.String())
curlCommand.WriteString("'")

for name, values := range req.Header {
for _, value := range values {
curlCommand.WriteString(" -H '")
curlCommand.WriteString(name)
curlCommand.WriteString(": ")
curlCommand.WriteString(value)
curlCommand.WriteString("'")
}
}

if req.Body != nil {
bodyBytes, _ := io.ReadAll(req.Body)
req.Body = io.NopCloser(bytes.NewBuffer(bodyBytes))
if len(bodyBytes) > 0 {
curlCommand.WriteString(" --data '")
curlCommand.WriteString(string(bodyBytes))
curlCommand.WriteString("'")
}
}

return curlCommand.String()
}

// NewAPIClient returns APIClient instance
Expand Down

0 comments on commit cf76690

Please sign in to comment.