fix: query params support + remove duplicate response wrappers + fix tests

This commit is contained in:
2026-07-28 16:45:45 +08:00
parent 4e348031a6
commit 284a503541
6 changed files with 43 additions and 49 deletions
+25 -12
View File
@@ -7,6 +7,7 @@ import (
"fmt"
"io"
"net/http"
"net/url"
"time"
)
@@ -36,23 +37,35 @@ type apiResponse struct {
}
func (c *client) get(ctx context.Context, path string, result any) error {
return c.do(ctx, "GET", path, nil, result)
return c.do(ctx, "GET", path, nil, result, nil)
}
func (c *client) getWithQuery(ctx context.Context, path string, query map[string]string, result any) error {
return c.do(ctx, "GET", path, nil, result, query)
}
func (c *client) post(ctx context.Context, path string, body, result any) error {
return c.do(ctx, "POST", path, body, result)
return c.do(ctx, "POST", path, body, result, nil)
}
func (c *client) patch(ctx context.Context, path string, body, result any) error {
return c.do(ctx, "PATCH", path, body, result)
return c.do(ctx, "PATCH", path, body, result, nil)
}
func (c *client) delete(ctx context.Context, path string, result any) error {
return c.do(ctx, "DELETE", path, nil, result)
return c.do(ctx, "DELETE", path, nil, result, nil)
}
func (c *client) do(ctx context.Context, method, path string, body, result any) error {
url := c.baseURL + path
func (c *client) do(ctx context.Context, method, path string, body, result any, query map[string]string) error {
u := c.baseURL + path
if len(query) > 0 {
params := url.Values{}
for k, v := range query {
params.Set(k, v)
}
u += "?" + params.Encode()
}
var bodyReader io.Reader
if body != nil {
@@ -63,7 +76,7 @@ func (c *client) do(ctx context.Context, method, path string, body, result any)
bodyReader = bytes.NewReader(b)
}
req, err := http.NewRequestWithContext(ctx, method, url, bodyReader)
req, err := http.NewRequestWithContext(ctx, method, u, bodyReader)
if err != nil {
return fmt.Errorf("create request: %w", err)
}
@@ -88,7 +101,7 @@ func (c *client) do(ctx context.Context, method, path string, body, result any)
return &APIError{
StatusCode: resp.StatusCode,
Method: method,
URL: url,
URL: u,
Body: respBody,
APICode: apiResp.Code,
APIMsg: apiResp.Msg,
@@ -98,14 +111,14 @@ func (c *client) do(ctx context.Context, method, path string, body, result any)
return &APIError{
StatusCode: resp.StatusCode,
Method: method,
URL: url,
URL: u,
Body: respBody,
}
}
if result != nil {
if err := json.Unmarshal(respBody, result); err != nil {
return fmt.Errorf("unmarshal response: %w", err)
if result != nil && apiResp.Data != nil {
if err := json.Unmarshal(apiResp.Data, result); err != nil {
return fmt.Errorf("unmarshal data: %w", err)
}
}
return nil