Files
.github
.vscode
docker
internal
app
applicant
certificate
deployer
domain
notify
pkg
core
logging
sdk3rd
1panel
azure
baiducloud
baishan
btpanel
btwaf
bunny
cachefly
cdnfly
api.go
client.go
models.go
cmcc
dcloud
dnsla
dogecloud
edgio
flexcdn
gcore
gname
goedge
lecdn
netlify
qiniu
rainyun
ratpanel
safeline
ucloud
upyun
volcengine
wangsu
utils
repository
rest
scheduler
statistics
workflow
migrations
ui
.dockerignore
.editorconfig
.gitignore
.goreleaser.yml
CHANGELOG.md
CONTRIBUTING.md
CONTRIBUTING_EN.md
Dockerfile
LICENSE.md
Makefile
README.md
README_EN.md
go.mod
go.sum
main.go
nixpacks.toml
certimate/internal/pkg/sdk3rd/cdnfly/client.go

87 lines
2.1 KiB
Go

package cdnfly
import (
"crypto/tls"
"encoding/json"
"fmt"
"net/http"
"strings"
"time"
"github.com/go-resty/resty/v2"
)
type Client struct {
client *resty.Client
}
func NewClient(serverUrl, apiKey, apiSecret string) *Client {
client := resty.New().
SetBaseURL(strings.TrimRight(serverUrl, "/")).
SetHeader("User-Agent", "certimate").
SetHeader("API-Key", apiKey).
SetHeader("API-Secret", apiSecret)
return &Client{
client: client,
}
}
func (c *Client) WithTimeout(timeout time.Duration) *Client {
c.client.SetTimeout(timeout)
return c
}
func (c *Client) WithTLSConfig(config *tls.Config) *Client {
c.client.SetTLSClientConfig(config)
return c
}
func (c *Client) sendRequest(method string, path string, params interface{}) (*resty.Response, error) {
req := c.client.R()
if strings.EqualFold(method, http.MethodGet) {
qs := make(map[string]string)
if params != nil {
temp := make(map[string]any)
jsonb, _ := json.Marshal(params)
json.Unmarshal(jsonb, &temp)
for k, v := range temp {
if v != nil {
qs[k] = fmt.Sprintf("%v", v)
}
}
}
req = req.SetQueryParams(qs)
} else {
req = req.SetHeader("Content-Type", "application/json").SetBody(params)
}
resp, err := req.Execute(method, path)
if err != nil {
return resp, fmt.Errorf("cdnfly api error: failed to send request: %w", err)
} else if resp.IsError() {
return resp, fmt.Errorf("cdnfly api error: unexpected status code: %d, resp: %s", resp.StatusCode(), resp.String())
}
return resp, nil
}
func (c *Client) sendRequestWithResult(method string, path string, params interface{}, result BaseResponse) error {
resp, err := c.sendRequest(method, path, params)
if err != nil {
if resp != nil {
json.Unmarshal(resp.Body(), &result)
}
return err
}
if err := json.Unmarshal(resp.Body(), &result); err != nil {
return fmt.Errorf("cdnfly api error: failed to unmarshal response: %w", err)
} else if errcode := result.GetCode(); errcode != "" && errcode != "0" {
return fmt.Errorf("cdnfly api error: code='%s', message='%s'", errcode, result.GetMessage())
}
return nil
}