feat: HTTP debug logging in client.do()
This commit is contained in:
@@ -8,6 +8,7 @@ import (
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"time"
|
||||
)
|
||||
|
||||
@@ -17,9 +18,10 @@ type client struct {
|
||||
httpClient *http.Client
|
||||
baseURL string
|
||||
apiKey string
|
||||
debug bool
|
||||
}
|
||||
|
||||
func newClient(endpoint, apiKey string) *client {
|
||||
func newClient(endpoint, apiKey string, debug bool) *client {
|
||||
if endpoint == "" {
|
||||
endpoint = defaultEndpoint
|
||||
}
|
||||
@@ -27,6 +29,7 @@ func newClient(endpoint, apiKey string) *client {
|
||||
httpClient: &http.Client{Timeout: 30 * time.Second},
|
||||
baseURL: endpoint,
|
||||
apiKey: apiKey,
|
||||
debug: debug,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -85,14 +88,23 @@ func (c *client) do(ctx context.Context, method, path string, body, result any,
|
||||
}
|
||||
|
||||
var bodyReader io.Reader
|
||||
var bodyBytes []byte
|
||||
if body != nil {
|
||||
b, err := json.Marshal(body)
|
||||
if err != nil {
|
||||
return fmt.Errorf("marshal request: %w", err)
|
||||
}
|
||||
bodyBytes = b
|
||||
bodyReader = bytes.NewReader(b)
|
||||
}
|
||||
|
||||
if c.debug {
|
||||
fmt.Fprintf(os.Stderr, "[debug] > %s %s\n", method, u)
|
||||
if bodyBytes != nil {
|
||||
fmt.Fprintf(os.Stderr, "[debug] %s\n", bodyBytes)
|
||||
}
|
||||
}
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, method, u, bodyReader)
|
||||
if err != nil {
|
||||
return fmt.Errorf("create request: %w", err)
|
||||
@@ -101,6 +113,7 @@ func (c *client) do(ctx context.Context, method, path string, body, result any,
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Accept", "application/json")
|
||||
|
||||
start := time.Now()
|
||||
resp, err := c.httpClient.Do(req)
|
||||
if err != nil {
|
||||
return fmt.Errorf("request failed: %w", err)
|
||||
@@ -112,6 +125,11 @@ func (c *client) do(ctx context.Context, method, path string, body, result any,
|
||||
return fmt.Errorf("read response: %w", err)
|
||||
}
|
||||
|
||||
if c.debug {
|
||||
fmt.Fprintf(os.Stderr, "[debug] < %d %s %s\n", resp.StatusCode, http.StatusText(resp.StatusCode), time.Since(start).Round(time.Millisecond))
|
||||
fmt.Fprintf(os.Stderr, "[debug] %s\n", respBody)
|
||||
}
|
||||
|
||||
var apiResp apiResponse
|
||||
if err := json.Unmarshal(respBody, &apiResp); err == nil {
|
||||
// Rainyun uses code:200 and code:0 both as success indicators
|
||||
|
||||
Reference in New Issue
Block a user