mirror of
https://github.com/usual2970/certimate.git
synced 2025-06-08 21:49:52 +00:00
80 lines
1.8 KiB
Go
80 lines
1.8 KiB
Go
package cdnflysdk
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"net/http"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/go-resty/resty/v2"
|
|
)
|
|
|
|
type Client struct {
|
|
apiHost string
|
|
apiKey string
|
|
apiSecret string
|
|
|
|
client *resty.Client
|
|
}
|
|
|
|
func NewClient(apiHost, apiKey, apiSecret string) *Client {
|
|
client := resty.New()
|
|
|
|
return &Client{
|
|
apiHost: strings.TrimRight(apiHost, "/"),
|
|
apiKey: apiKey,
|
|
apiSecret: apiSecret,
|
|
client: client,
|
|
}
|
|
}
|
|
|
|
func (c *Client) WithTimeout(timeout time.Duration) *Client {
|
|
c.client.SetTimeout(timeout)
|
|
return c
|
|
}
|
|
|
|
func (c *Client) sendRequest(method string, path string, params map[string]any) (*resty.Response, error) {
|
|
req := c.client.R()
|
|
req.Method = method
|
|
req.URL = c.apiHost + path
|
|
req = req.
|
|
SetHeader("api-key", c.apiKey).
|
|
SetHeader("api-secret", c.apiSecret)
|
|
if strings.EqualFold(method, http.MethodGet) {
|
|
data := make(map[string]string)
|
|
for k, v := range params {
|
|
data[k] = fmt.Sprintf("%v", v)
|
|
}
|
|
req = req.SetQueryParams(data)
|
|
} else {
|
|
req = req.
|
|
SetHeader("Content-Type", "application/json").
|
|
SetBody(params)
|
|
}
|
|
|
|
resp, err := req.Send()
|
|
if err != nil {
|
|
return nil, fmt.Errorf("cdnfly api error: failed to send request: %w", err)
|
|
} else if resp.IsError() {
|
|
return nil, fmt.Errorf("cdnfly api error: unexpected status code: %d, %s", resp.StatusCode(), resp.Body())
|
|
}
|
|
|
|
return resp, nil
|
|
}
|
|
|
|
func (c *Client) sendRequestWithResult(method string, path string, params map[string]any, result BaseResponse) error {
|
|
resp, err := c.sendRequest(method, path, params)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
if err := json.Unmarshal(resp.Body(), &result); err != nil {
|
|
return fmt.Errorf("cdnfly api error: failed to parse response: %w", err)
|
|
} else if errcode := result.GetCode(); errcode != "" && errcode != "0" {
|
|
return fmt.Errorf("cdnfly api error: %s - %s", errcode, result.GetMessage())
|
|
}
|
|
|
|
return nil
|
|
}
|