feat: new deployment provider: lecdn

This commit is contained in:
Fu Diwei
2025-05-19 22:51:17 +08:00
parent a66e1c04c9
commit c9e6bd0c2f
40 changed files with 1128 additions and 155 deletions

View File

@@ -53,6 +53,7 @@ import (
pJDCloudLive "github.com/usual2970/certimate/internal/pkg/core/deployer/providers/jdcloud-live"
pJDCloudVOD "github.com/usual2970/certimate/internal/pkg/core/deployer/providers/jdcloud-vod"
pK8sSecret "github.com/usual2970/certimate/internal/pkg/core/deployer/providers/k8s-secret"
pLeCDN "github.com/usual2970/certimate/internal/pkg/core/deployer/providers/lecdn"
pLocal "github.com/usual2970/certimate/internal/pkg/core/deployer/providers/local"
pNetlifySite "github.com/usual2970/certimate/internal/pkg/core/deployer/providers/netlify-site"
pProxmoxVE "github.com/usual2970/certimate/internal/pkg/core/deployer/providers/proxmoxve"
@@ -729,6 +730,27 @@ func createDeployerProvider(options *deployerProviderOptions) (deployer.Deployer
}
}
case domain.DeploymentProviderTypeLeCDN:
{
access := domain.AccessConfigForLeCDN{}
if err := maputil.Populate(options.ProviderAccessConfig, &access); err != nil {
return nil, fmt.Errorf("failed to populate provider access config: %w", err)
}
deployer, err := pLeCDN.NewDeployer(&pLeCDN.DeployerConfig{
ApiUrl: access.ApiUrl,
ApiVersion: access.ApiVersion,
ApiRole: access.ApiRole,
Username: access.Username,
Password: access.Password,
AllowInsecureConnections: access.AllowInsecureConnections,
ResourceType: pLeCDN.ResourceType(maputil.GetString(options.ProviderServiceConfig, "resourceType")),
CertificateId: maputil.GetInt64(options.ProviderServiceConfig, "certificateId"),
ClientId: maputil.GetInt64(options.ProviderServiceConfig, "clientId"),
})
return deployer, err
}
case domain.DeploymentProviderTypeLocal:
{
deployer, err := pLocal.NewDeployer(&pLocal.DeployerConfig{

View File

@@ -193,6 +193,15 @@ type AccessConfigForLarkBot struct {
WebhookUrl string `json:"webhookUrl"`
}
type AccessConfigForLeCDN struct {
ApiUrl string `json:"apiUrl"`
ApiVersion string `json:"apiVersion"`
ApiRole string `json:"apiRole"`
Username string `json:"username"`
Password string `json:"password"`
AllowInsecureConnections bool `json:"allowInsecureConnections,omitempty"`
}
type AccessConfigForMattermost struct {
ServerUrl string `json:"serverUrl"`
Username string `json:"username"`

View File

@@ -49,7 +49,7 @@ const (
AccessProviderTypeLarkBot = AccessProviderType("larkbot")
AccessProviderTypeLetsEncrypt = AccessProviderType("letsencrypt")
AccessProviderTypeLetsEncryptStaging = AccessProviderType("letsencryptstaging")
AccessProviderTypeLeCDN = AccessProviderType("lecdn") // LeCDN预留
AccessProviderTypeLeCDN = AccessProviderType("lecdn")
AccessProviderTypeLocal = AccessProviderType("local")
AccessProviderTypeMattermost = AccessProviderType("mattermost")
AccessProviderTypeNamecheap = AccessProviderType("namecheap")
@@ -208,7 +208,7 @@ const (
DeploymentProviderTypeJDCloudLive = DeploymentProviderType(AccessProviderTypeJDCloud + "-live")
DeploymentProviderTypeJDCloudVOD = DeploymentProviderType(AccessProviderTypeJDCloud + "-vod")
DeploymentProviderTypeKubernetesSecret = DeploymentProviderType(AccessProviderTypeKubernetes + "-secret")
DeploymentProviderTypeLeCDN = DeploymentProviderType(AccessProviderTypeLeCDN) // LeCDN预留
DeploymentProviderTypeLeCDN = DeploymentProviderType(AccessProviderTypeLeCDN)
DeploymentProviderTypeLocal = DeploymentProviderType(AccessProviderTypeLocal)
DeploymentProviderTypeNetlifySite = DeploymentProviderType(AccessProviderTypeNetlify + "-site")
DeploymentProviderTypeProxmoxVE = DeploymentProviderType(AccessProviderTypeProxmoxVE)

View File

@@ -16,6 +16,7 @@ type DeployerConfig struct {
// 1Panel 地址。
ApiUrl string `json:"apiUrl"`
// 1Panel 版本。
// 可取值 "v1"、"v2"。
ApiVersion string `json:"apiVersion"`
// 1Panel 接口密钥。
ApiKey string `json:"apiKey"`

View File

@@ -19,6 +19,7 @@ type DeployerConfig struct {
// 1Panel 地址。
ApiUrl string `json:"apiUrl"`
// 1Panel 版本。
// 可取值 "v1"、"v2"。
ApiVersion string `json:"apiVersion"`
// 1Panel 接口密钥。
ApiKey string `json:"apiKey"`

View File

@@ -18,7 +18,7 @@ var (
fAccessKeySecret string
fRegion string
fLoadbalancerId string
fListenerPort int
fListenerPort int64
fDomain string
)
@@ -31,7 +31,7 @@ func init() {
flag.StringVar(&fAccessKeySecret, argsPrefix+"ACCESSKEYSECRET", "", "")
flag.StringVar(&fRegion, argsPrefix+"REGION", "", "")
flag.StringVar(&fLoadbalancerId, argsPrefix+"LOADBALANCERID", "", "")
flag.IntVar(&fListenerPort, argsPrefix+"LISTENERPORT", 443, "")
flag.Int64Var(&fListenerPort, argsPrefix+"LISTENERPORT", 443, "")
flag.StringVar(&fDomain, argsPrefix+"DOMAIN", "", "")
}

View File

@@ -22,6 +22,7 @@ type DeployerConfig struct {
// 阿里云地域。
Region string `json:"region"`
// 服务版本。
// 可取值 "2.0"、"3.0"。
ServiceVersion string `json:"serviceVersion"`
// 自定义域名(支持泛域名)。
Domain string `json:"domain"`

View File

@@ -19,6 +19,7 @@ type DeployerConfig struct {
// FlexCDN URL。
ApiUrl string `json:"apiUrl"`
// FlexCDN 用户角色。
// 可取值 "user"、"admin"。
ApiRole string `json:"apiRole"`
// FlexCDN AccessKeyId。
AccessKeyId string `json:"accessKeyId"`

View File

@@ -17,7 +17,7 @@ var (
fApiUrl string
fAccessKeyId string
fAccessKey string
fCertificateId int
fCertificateId int64
)
func init() {
@@ -28,7 +28,7 @@ func init() {
flag.StringVar(&fApiUrl, argsPrefix+"APIURL", "", "")
flag.StringVar(&fAccessKeyId, argsPrefix+"ACCESSKEYID", "", "")
flag.StringVar(&fAccessKey, argsPrefix+"ACCESSKEY", "", "")
flag.IntVar(&fCertificateId, argsPrefix+"CERTIFICATEID", 0, "")
flag.Int64Var(&fCertificateId, argsPrefix+"CERTIFICATEID", 0, "")
}
/*
@@ -45,7 +45,7 @@ Shell command to run this test:
func TestDeploy(t *testing.T) {
flag.Parse()
t.Run("Deploy", func(t *testing.T) {
t.Run("Deploy_ToCertificate", func(t *testing.T) {
t.Log(strings.Join([]string{
"args:",
fmt.Sprintf("INPUTCERTPATH: %v", fInputCertPath),
@@ -63,7 +63,7 @@ func TestDeploy(t *testing.T) {
AccessKey: fAccessKey,
AllowInsecureConnections: true,
ResourceType: provider.RESOURCE_TYPE_CERTIFICATE,
CertificateId: int64(fCertificateId),
CertificateId: fCertificateId,
})
if err != nil {
t.Errorf("err: %+v", err)

View File

@@ -19,6 +19,7 @@ type DeployerConfig struct {
// GoEdge URL。
ApiUrl string `json:"apiUrl"`
// GoEdge 用户角色。
// 可取值 "user"、"admin"。
ApiRole string `json:"apiRole"`
// GoEdge AccessKeyId。
AccessKeyId string `json:"accessKeyId"`

View File

@@ -17,7 +17,7 @@ var (
fApiUrl string
fAccessKeyId string
fAccessKey string
fCertificateId int
fCertificateId int64
)
func init() {
@@ -28,7 +28,7 @@ func init() {
flag.StringVar(&fApiUrl, argsPrefix+"APIURL", "", "")
flag.StringVar(&fAccessKeyId, argsPrefix+"ACCESSKEYID", "", "")
flag.StringVar(&fAccessKey, argsPrefix+"ACCESSKEY", "", "")
flag.IntVar(&fCertificateId, argsPrefix+"CERTIFICATEID", 0, "")
flag.Int64Var(&fCertificateId, argsPrefix+"CERTIFICATEID", 0, "")
}
/*
@@ -45,7 +45,7 @@ Shell command to run this test:
func TestDeploy(t *testing.T) {
flag.Parse()
t.Run("Deploy", func(t *testing.T) {
t.Run("Deploy_ToCertificate", func(t *testing.T) {
t.Log(strings.Join([]string{
"args:",
fmt.Sprintf("INPUTCERTPATH: %v", fInputCertPath),
@@ -63,7 +63,7 @@ func TestDeploy(t *testing.T) {
AccessKey: fAccessKey,
AllowInsecureConnections: true,
ResourceType: provider.RESOURCE_TYPE_CERTIFICATE,
CertificateId: int64(fCertificateId),
CertificateId: fCertificateId,
})
if err != nil {
t.Errorf("err: %+v", err)

View File

@@ -0,0 +1,8 @@
package lecdn
type ResourceType string
const (
// 资源类型:替换指定证书。
RESOURCE_TYPE_CERTIFICATE = ResourceType("certificate")
)

View File

@@ -0,0 +1,176 @@
package lecdn
import (
"context"
"crypto/tls"
"errors"
"fmt"
"log/slog"
"net/url"
"time"
"github.com/usual2970/certimate/internal/pkg/core/deployer"
leclientsdkv3 "github.com/usual2970/certimate/internal/pkg/sdk3rd/lecdn/v3/client"
lemastersdkv3 "github.com/usual2970/certimate/internal/pkg/sdk3rd/lecdn/v3/master"
)
type DeployerConfig struct {
// LeCDN URL。
ApiUrl string `json:"apiUrl"`
// LeCDN 版本。
// 可取值 "v3"。
ApiVersion string `json:"apiVersion"`
// LeCDN 用户角色。
// 可取值 "client"、"master"。
ApiRole string `json:"apiRole"`
// LeCDN 用户名。
Username string `json:"accessKeyId"`
// LeCDN 用户密码。
Password string `json:"accessKey"`
// 是否允许不安全的连接。
AllowInsecureConnections bool `json:"allowInsecureConnections,omitempty"`
// 部署资源类型。
ResourceType ResourceType `json:"resourceType"`
// 证书 ID。
// 部署资源类型为 [RESOURCE_TYPE_CERTIFICATE] 时必填。
CertificateId int64 `json:"certificateId,omitempty"`
// 客户 ID。
// 部署资源类型为 [RESOURCE_TYPE_CERTIFICATE] 时选填。
ClientId int64 `json:"clientId,omitempty"`
}
type DeployerProvider struct {
config *DeployerConfig
logger *slog.Logger
sdkClient interface{}
}
var _ deployer.Deployer = (*DeployerProvider)(nil)
const (
apiVersionV3 = "v3"
apiRoleClient = "client"
apiRoleMaster = "master"
)
func NewDeployer(config *DeployerConfig) (*DeployerProvider, error) {
if config == nil {
panic("config is nil")
}
client, err := createSdkClient(config.ApiUrl, config.ApiVersion, config.ApiRole, config.Username, config.Password, config.AllowInsecureConnections)
if err != nil {
return nil, fmt.Errorf("failed to create sdk client: %w", err)
}
return &DeployerProvider{
config: config,
logger: slog.Default(),
sdkClient: client,
}, nil
}
func (d *DeployerProvider) WithLogger(logger *slog.Logger) deployer.Deployer {
if logger == nil {
d.logger = slog.Default()
} else {
d.logger = logger
}
return d
}
func (d *DeployerProvider) Deploy(ctx context.Context, certPEM string, privkeyPEM string) (*deployer.DeployResult, error) {
// 根据部署资源类型决定部署方式
switch d.config.ResourceType {
case RESOURCE_TYPE_CERTIFICATE:
if err := d.deployToCertificate(ctx, certPEM, privkeyPEM); err != nil {
return nil, err
}
default:
return nil, fmt.Errorf("unsupported resource type '%s'", d.config.ResourceType)
}
return &deployer.DeployResult{}, nil
}
func (d *DeployerProvider) deployToCertificate(ctx context.Context, certPEM string, privkeyPEM string) error {
if d.config.CertificateId == 0 {
return errors.New("config `certificateId` is required")
}
// 修改证书
// REF: https://wdk0pwf8ul.feishu.cn/wiki/YE1XwCRIHiLYeKkPupgcXrlgnDd
switch sdkClient := d.sdkClient.(type) {
case *leclientsdkv3.Client:
updateSSLCertReq := &leclientsdkv3.UpdateCertificateRequest{
Name: fmt.Sprintf("certimate-%d", time.Now().UnixMilli()),
Description: "upload from certimate",
Type: "upload",
SSLPEM: certPEM,
SSLKey: privkeyPEM,
AutoRenewal: false,
}
updateSSLCertResp, err := sdkClient.UpdateCertificate(d.config.CertificateId, updateSSLCertReq)
d.logger.Debug("sdk request 'lecdn.UpdateCertificate'", slog.Int64("certId", d.config.CertificateId), slog.Any("request", updateSSLCertReq), slog.Any("response", updateSSLCertResp))
if err != nil {
return fmt.Errorf("failed to execute sdk request 'lecdn.UpdateCertificate': %w", err)
}
case *lemastersdkv3.Client:
updateSSLCertReq := &lemastersdkv3.UpdateCertificateRequest{
ClientId: d.config.ClientId,
Name: fmt.Sprintf("certimate-%d", time.Now().UnixMilli()),
Description: "upload from certimate",
Type: "upload",
SSLPEM: certPEM,
SSLKey: privkeyPEM,
AutoRenewal: false,
}
updateSSLCertResp, err := sdkClient.UpdateCertificate(d.config.CertificateId, updateSSLCertReq)
d.logger.Debug("sdk request 'lecdn.UpdateCertificate'", slog.Int64("certId", d.config.CertificateId), slog.Any("request", updateSSLCertReq), slog.Any("response", updateSSLCertResp))
if err != nil {
return fmt.Errorf("failed to execute sdk request 'lecdn.UpdateCertificate': %w", err)
}
default:
panic("sdk client is not implemented")
}
return nil
}
func createSdkClient(apiUrl, apiVersion, apiRole, username, password string, skipTlsVerify bool) (interface{}, error) {
if _, err := url.Parse(apiUrl); err != nil {
return nil, errors.New("invalid lecdn api url")
}
if username == "" {
return nil, errors.New("invalid lecdn username")
}
if password == "" {
return nil, errors.New("invalid lecdn password")
}
if apiVersion == apiVersionV3 && apiRole == apiRoleClient {
// v3 版客户端
client := leclientsdkv3.NewClient(apiUrl, username, password)
if skipTlsVerify {
client.WithTLSConfig(&tls.Config{InsecureSkipVerify: true})
}
return client, nil
} else if apiVersion == apiVersionV3 && apiRole == apiRoleMaster {
// v3 版主控端
client := lemastersdkv3.NewClient(apiUrl, username, password)
if skipTlsVerify {
client.WithTLSConfig(&tls.Config{InsecureSkipVerify: true})
}
return client, nil
}
return nil, fmt.Errorf("invalid lecdn api version or user role")
}

View File

@@ -0,0 +1,87 @@
package lecdn_test
import (
"context"
"flag"
"fmt"
"os"
"strings"
"testing"
provider "github.com/usual2970/certimate/internal/pkg/core/deployer/providers/lecdn"
)
var (
fInputCertPath string
fInputKeyPath string
fApiUrl string
fApiVersion string
fUsername string
fPassword string
fCertificateId int64
)
func init() {
argsPrefix := "CERTIMATE_DEPLOYER_LECDN_"
flag.StringVar(&fInputCertPath, argsPrefix+"INPUTCERTPATH", "", "")
flag.StringVar(&fInputKeyPath, argsPrefix+"INPUTKEYPATH", "", "")
flag.StringVar(&fApiUrl, argsPrefix+"APIURL", "", "")
flag.StringVar(&fApiVersion, argsPrefix+"APIVERSION", "v3", "")
flag.StringVar(&fUsername, argsPrefix+"USERNAME", "", "")
flag.StringVar(&fPassword, argsPrefix+"PASSWORD", "", "")
flag.Int64Var(&fCertificateId, argsPrefix+"CERTIFICATEID", 0, "")
}
/*
Shell command to run this test:
go test -v ./lecdn_test.go -args \
--CERTIMATE_DEPLOYER_LECDN_INPUTCERTPATH="/path/to/your-input-cert.pem" \
--CERTIMATE_DEPLOYER_LECDN_INPUTKEYPATH="/path/to/your-input-key.pem" \
--CERTIMATE_DEPLOYER_LECDN_APIURL="http://127.0.0.1:5090" \
--CERTIMATE_DEPLOYER_LECDN_USERNAME="your-username" \
--CERTIMATE_DEPLOYER_LECDN_PASSWORD="your-password" \
--CERTIMATE_DEPLOYER_LECDN_CERTIFICATEID="your-cerficiate-id"
*/
func TestDeploy(t *testing.T) {
flag.Parse()
t.Run("Deploy_ToCertificate", func(t *testing.T) {
t.Log(strings.Join([]string{
"args:",
fmt.Sprintf("INPUTCERTPATH: %v", fInputCertPath),
fmt.Sprintf("INPUTKEYPATH: %v", fInputKeyPath),
fmt.Sprintf("APIURL: %v", fApiUrl),
fmt.Sprintf("APIVERSION: %v", fApiVersion),
fmt.Sprintf("USERNAME: %v", fUsername),
fmt.Sprintf("PASSWORD: %v", fPassword),
fmt.Sprintf("CERTIFICATEID: %v", fCertificateId),
}, "\n"))
deployer, err := provider.NewDeployer(&provider.DeployerConfig{
ApiUrl: fApiUrl,
ApiVersion: fApiVersion,
ApiRole: "user",
Username: fUsername,
Password: fPassword,
AllowInsecureConnections: true,
ResourceType: provider.RESOURCE_TYPE_CERTIFICATE,
CertificateId: fCertificateId,
})
if err != nil {
t.Errorf("err: %+v", err)
return
}
fInputCertData, _ := os.ReadFile(fInputCertPath)
fInputKeyData, _ := os.ReadFile(fInputKeyPath)
res, err := deployer.Deploy(context.Background(), string(fInputCertData), string(fInputKeyData))
if err != nil {
t.Errorf("err: %+v", err)
return
}
t.Logf("ok: %v", res)
})
}

View File

@@ -16,7 +16,7 @@ var (
fInputKeyPath string
fApiUrl string
fApiToken string
fCertificateId int
fCertificateId int64
)
func init() {
@@ -26,7 +26,7 @@ func init() {
flag.StringVar(&fInputKeyPath, argsPrefix+"INPUTKEYPATH", "", "")
flag.StringVar(&fApiUrl, argsPrefix+"APIURL", "", "")
flag.StringVar(&fApiToken, argsPrefix+"APITOKEN", "", "")
flag.IntVar(&fCertificateId, argsPrefix+"CERTIFICATEID", 0, "")
flag.Int64Var(&fCertificateId, argsPrefix+"CERTIFICATEID", 0, "")
}
/*

View File

@@ -15,7 +15,7 @@ var (
fInputCertPath string
fInputKeyPath string
fSshHost string
fSshPort int
fSshPort int64
fSshUsername string
fSshPassword string
fOutputCertPath string
@@ -28,7 +28,7 @@ func init() {
flag.StringVar(&fInputCertPath, argsPrefix+"INPUTCERTPATH", "", "")
flag.StringVar(&fInputKeyPath, argsPrefix+"INPUTKEYPATH", "", "")
flag.StringVar(&fSshHost, argsPrefix+"SSHHOST", "", "")
flag.IntVar(&fSshPort, argsPrefix+"SSHPORT", 0, "")
flag.Int64Var(&fSshPort, argsPrefix+"SSHPORT", 0, "")
flag.StringVar(&fSshUsername, argsPrefix+"SSHUSERNAME", "", "")
flag.StringVar(&fSshPassword, argsPrefix+"SSHPASSWORD", "", "")
flag.StringVar(&fOutputCertPath, argsPrefix+"OUTPUTCERTPATH", "", "")

View File

@@ -17,7 +17,7 @@ const (
var (
fSmtpHost string
fSmtpPort int
fSmtpPort int64
fSmtpTLS bool
fUsername string
fPassword string
@@ -29,7 +29,7 @@ func init() {
argsPrefix := "CERTIMATE_NOTIFIER_EMAIL_"
flag.StringVar(&fSmtpHost, argsPrefix+"SMTPHOST", "", "")
flag.IntVar(&fSmtpPort, argsPrefix+"SMTPPORT", 0, "")
flag.Int64Var(&fSmtpPort, argsPrefix+"SMTPPORT", 0, "")
flag.BoolVar(&fSmtpTLS, argsPrefix+"SMTPTLS", false, "")
flag.StringVar(&fUsername, argsPrefix+"USERNAME", "", "")
flag.StringVar(&fPassword, argsPrefix+"PASSWORD", "", "")

View File

@@ -7,7 +7,13 @@ import (
"time"
)
func (c *Client) getAccessToken() error {
func (c *Client) ensureAccessTokenExists() error {
c.accessTokenMtx.Lock()
defer c.accessTokenMtx.Unlock()
if c.accessToken != "" && c.accessTokenExp.After(time.Now()) {
return nil
}
req := &getAPIAccessTokenRequest{
Type: c.apiRole,
AccessKeyId: c.accessKeyId,
@@ -22,22 +28,18 @@ func (c *Client) getAccessToken() error {
if err := json.Unmarshal(res.Body(), &resp); err != nil {
return fmt.Errorf("flexcdn api error: failed to unmarshal response: %w", err)
} else if resp.GetCode() != 200 {
return fmt.Errorf("flexcdn get access token failed: code: %d, message: %s", resp.GetCode(), resp.GetMessage())
return fmt.Errorf("flexcdn get access token failed: code='%d', message='%s'", resp.GetCode(), resp.GetMessage())
}
c.accessTokenMtx.Lock()
c.accessToken = resp.Data.Token
c.accessTokenExp = time.Unix(resp.Data.ExpiresAt, 0)
c.accessTokenMtx.Unlock()
return nil
}
func (c *Client) UpdateSSLCert(req *UpdateSSLCertRequest) (*UpdateSSLCertResponse, error) {
if c.accessToken == "" || c.accessTokenExp.Before(time.Now()) {
if err := c.getAccessToken(); err != nil {
return nil, err
}
if err := c.ensureAccessTokenExists(); err != nil {
return nil, err
}
resp := &UpdateSSLCertResponse{}

View File

@@ -7,7 +7,13 @@ import (
"time"
)
func (c *Client) getAccessToken() error {
func (c *Client) ensureAccessTokenExists() error {
c.accessTokenMtx.Lock()
defer c.accessTokenMtx.Unlock()
if c.accessToken != "" && c.accessTokenExp.After(time.Now()) {
return nil
}
req := &getAPIAccessTokenRequest{
Type: c.apiRole,
AccessKeyId: c.accessKeyId,
@@ -22,22 +28,18 @@ func (c *Client) getAccessToken() error {
if err := json.Unmarshal(res.Body(), &resp); err != nil {
return fmt.Errorf("goedge api error: failed to unmarshal response: %w", err)
} else if resp.GetCode() != 200 {
return fmt.Errorf("goedge get access token failed: code: %d, message: %s", resp.GetCode(), resp.GetMessage())
return fmt.Errorf("goedge get access token failed: code='%d', message='%s'", resp.GetCode(), resp.GetMessage())
}
c.accessTokenMtx.Lock()
c.accessToken = resp.Data.Token
c.accessTokenExp = time.Unix(resp.Data.ExpiresAt, 0)
c.accessTokenMtx.Unlock()
return nil
}
func (c *Client) UpdateSSLCert(req *UpdateSSLCertRequest) (*UpdateSSLCertResponse, error) {
if c.accessToken == "" || c.accessTokenExp.Before(time.Now()) {
if err := c.getAccessToken(); err != nil {
return nil, err
}
if err := c.ensureAccessTokenExists(); err != nil {
return nil, err
}
resp := &UpdateSSLCertResponse{}

View File

@@ -0,0 +1,49 @@
package client
import (
"encoding/json"
"fmt"
"net/http"
)
func (c *Client) ensureAccessTokenExists() error {
c.accessTokenMtx.Lock()
defer c.accessTokenMtx.Unlock()
if c.accessToken != "" {
return nil
}
req := &loginRequest{
Username: c.username,
Password: c.password,
}
res, err := c.sendRequest(http.MethodPost, "/login", req)
if err != nil {
return err
}
resp := &loginResponse{}
if err := json.Unmarshal(res.Body(), &resp); err != nil {
return fmt.Errorf("lecdn api error: failed to unmarshal response: %w", err)
} else if resp.GetCode() != 200 {
return fmt.Errorf("lecdn get token failed: code='%d', message='%s'", resp.GetCode(), resp.GetMessage())
}
c.accessToken = resp.Data.Token
return nil
}
func (c *Client) UpdateCertificate(certId int64, req *UpdateCertificateRequest) (*UpdateCertificateResponse, error) {
if certId == 0 {
return nil, fmt.Errorf("lecdn api error: invalid parameter: CertId")
}
if err := c.ensureAccessTokenExists(); err != nil {
return nil, err
}
resp := &UpdateCertificateResponse{}
err := c.sendRequestWithResult(http.MethodPut, fmt.Sprintf("/certificate/%d", certId), req, resp)
return resp, err
}

View File

@@ -0,0 +1,98 @@
package client
import (
"crypto/tls"
"encoding/json"
"fmt"
"net/http"
"strings"
"sync"
"time"
"github.com/go-resty/resty/v2"
)
type Client struct {
apiHost string
username string
password string
accessToken string
accessTokenMtx sync.Mutex
client *resty.Client
}
func NewClient(apiHost, username, password string) *Client {
client := resty.New()
return &Client{
apiHost: strings.TrimRight(apiHost, "/"),
username: username,
password: password,
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().SetBasicAuth(c.username, c.password)
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.
SetHeader("Authorization", "Bearer "+c.accessToken).
SetQueryParams(qs)
} else {
req = req.
SetHeader("Content-Type", "application/json").
SetHeader("Authorization", "Bearer "+c.accessToken).
SetBody(params)
}
resp, err := req.Execute(method, c.apiHost+"/prod-api"+path)
if err != nil {
return resp, fmt.Errorf("lecdn api error: failed to send request: %w", err)
} else if resp.IsError() {
return resp, fmt.Errorf("lecdn 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("lecdn api error: failed to unmarshal response: %w", err)
} else if errcode := result.GetCode(); errcode != 200 {
return fmt.Errorf("lecdn api error: code='%d', message='%s'", errcode, result.GetMessage())
}
return nil
}

View File

@@ -0,0 +1,46 @@
package client
type BaseResponse interface {
GetCode() int32
GetMessage() string
}
type baseResponse struct {
Code int32 `json:"code"`
Message string `json:"msg"`
}
func (r *baseResponse) GetCode() int32 {
return r.Code
}
func (r *baseResponse) GetMessage() string {
return r.Message
}
type loginRequest struct {
Username string `json:"username"`
Password string `json:"password"`
}
type loginResponse struct {
baseResponse
Data *struct {
UserId int64 `json:"user_id"`
Username string `json:"username"`
Token string `json:"token"`
} `json:"data,omitempty"`
}
type UpdateCertificateRequest struct {
Name string `json:"name"`
Description string `json:"description"`
Type string `json:"type"`
SSLPEM string `json:"ssl_pem"`
SSLKey string `json:"ssl_key"`
AutoRenewal bool `json:"auto_renewal"`
}
type UpdateCertificateResponse struct {
baseResponse
}

View File

@@ -0,0 +1,49 @@
package master
import (
"encoding/json"
"fmt"
"net/http"
)
func (c *Client) ensureAccessTokenExists() error {
c.accessTokenMtx.Lock()
defer c.accessTokenMtx.Unlock()
if c.accessToken != "" {
return nil
}
req := &loginRequest{
Username: c.username,
Password: c.password,
}
res, err := c.sendRequest(http.MethodPost, "/auth/login", req)
if err != nil {
return err
}
resp := &loginResponse{}
if err := json.Unmarshal(res.Body(), &resp); err != nil {
return fmt.Errorf("lecdn api error: failed to unmarshal response: %w", err)
} else if resp.GetCode() != 200 {
return fmt.Errorf("lecdn get token failed: code='%d', message='%s'", resp.GetCode(), resp.GetMessage())
}
c.accessToken = resp.Data.Token
return nil
}
func (c *Client) UpdateCertificate(certId int64, req *UpdateCertificateRequest) (*UpdateCertificateResponse, error) {
if certId == 0 {
return nil, fmt.Errorf("lecdn api error: invalid parameter: CertId")
}
if err := c.ensureAccessTokenExists(); err != nil {
return nil, err
}
resp := &UpdateCertificateResponse{}
err := c.sendRequestWithResult(http.MethodPut, fmt.Sprintf("/certificate/%d", certId), req, resp)
return resp, err
}

View File

@@ -0,0 +1,98 @@
package master
import (
"crypto/tls"
"encoding/json"
"fmt"
"net/http"
"strings"
"sync"
"time"
"github.com/go-resty/resty/v2"
)
type Client struct {
apiHost string
username string
password string
accessToken string
accessTokenMtx sync.Mutex
client *resty.Client
}
func NewClient(apiHost, username, password string) *Client {
client := resty.New()
return &Client{
apiHost: strings.TrimRight(apiHost, "/"),
username: username,
password: password,
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().SetBasicAuth(c.username, c.password)
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.
SetHeader("Authorization", "Bearer "+c.accessToken).
SetQueryParams(qs)
} else {
req = req.
SetHeader("Content-Type", "application/json").
SetHeader("Authorization", "Bearer "+c.accessToken).
SetBody(params)
}
resp, err := req.Execute(method, c.apiHost+"/prod-api"+path)
if err != nil {
return resp, fmt.Errorf("lecdn api error: failed to send request: %w", err)
} else if resp.IsError() {
return resp, fmt.Errorf("lecdn 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("lecdn api error: failed to unmarshal response: %w", err)
} else if errcode := result.GetCode(); errcode != 200 {
return fmt.Errorf("lecdn api error: code='%d', message='%s'", errcode, result.GetMessage())
}
return nil
}

View File

@@ -0,0 +1,47 @@
package master
type BaseResponse interface {
GetCode() int32
GetMessage() string
}
type baseResponse struct {
Code int32 `json:"code"`
Message string `json:"message"`
}
func (r *baseResponse) GetCode() int32 {
return r.Code
}
func (r *baseResponse) GetMessage() string {
return r.Message
}
type loginRequest struct {
Username string `json:"username"`
Password string `json:"password"`
}
type loginResponse struct {
baseResponse
Data *struct {
UserId int64 `json:"user_id"`
Username string `json:"username"`
Token string `json:"token"`
} `json:"data,omitempty"`
}
type UpdateCertificateRequest struct {
ClientId int64 `json:"client_id"`
Name string `json:"name"`
Description string `json:"description"`
Type string `json:"type"`
SSLPEM string `json:"ssl_pem"`
SSLKey string `json:"ssl_key"`
AutoRenewal bool `json:"auto_renewal"`
}
type UpdateCertificateResponse struct {
baseResponse
}

View File

@@ -7,7 +7,11 @@ import (
"net/http"
)
func (c *Client) getCookie() error {
func (c *Client) ensureCookieExists() error {
if c.loginCookie != "" {
return nil
}
req := &signinRequest{Username: c.username, Password: c.password}
res, err := c.sendRequest(http.MethodPost, "/accounts/signin/", req)
if err != nil {
@@ -27,10 +31,8 @@ func (c *Client) getCookie() error {
}
func (c *Client) UploadHttpsCertificate(req *UploadHttpsCertificateRequest) (*UploadHttpsCertificateResponse, error) {
if c.loginCookie == "" {
if err := c.getCookie(); err != nil {
return nil, err
}
if err := c.ensureCookieExists(); err != nil {
return nil, err
}
resp := &UploadHttpsCertificateResponse{}
@@ -39,10 +41,8 @@ func (c *Client) UploadHttpsCertificate(req *UploadHttpsCertificateRequest) (*Up
}
func (c *Client) GetHttpsCertificateManager(certificateId string) (*GetHttpsCertificateManagerResponse, error) {
if c.loginCookie == "" {
if err := c.getCookie(); err != nil {
return nil, err
}
if err := c.ensureCookieExists(); err != nil {
return nil, err
}
req := &GetHttpsCertificateManagerRequest{CertificateId: certificateId}
@@ -52,10 +52,8 @@ func (c *Client) GetHttpsCertificateManager(certificateId string) (*GetHttpsCert
}
func (c *Client) UpdateHttpsCertificateManager(req *UpdateHttpsCertificateManagerRequest) (*UpdateHttpsCertificateManagerResponse, error) {
if c.loginCookie == "" {
if err := c.getCookie(); err != nil {
return nil, err
}
if err := c.ensureCookieExists(); err != nil {
return nil, err
}
resp := &UpdateHttpsCertificateManagerResponse{}
@@ -64,10 +62,8 @@ func (c *Client) UpdateHttpsCertificateManager(req *UpdateHttpsCertificateManage
}
func (c *Client) GetHttpsServiceManager(domain string) (*GetHttpsServiceManagerResponse, error) {
if c.loginCookie == "" {
if err := c.getCookie(); err != nil {
return nil, err
}
if err := c.ensureCookieExists(); err != nil {
return nil, err
}
req := &GetHttpsServiceManagerRequest{Domain: domain}
@@ -77,10 +73,8 @@ func (c *Client) GetHttpsServiceManager(domain string) (*GetHttpsServiceManagerR
}
func (c *Client) MigrateHttpsDomain(req *MigrateHttpsDomainRequest) (*MigrateHttpsDomainResponse, error) {
if c.loginCookie == "" {
if err := c.getCookie(); err != nil {
return nil, err
}
if err := c.ensureCookieExists(); err != nil {
return nil, err
}
resp := &MigrateHttpsDomainResponse{}

View File

@@ -68,31 +68,42 @@ func GetOrDefaultInt32(dict map[string]any, key string, defaultValue int32) int3
}
if value, ok := dict[key]; ok {
if result, ok := value.(int32); ok {
if result != 0 {
return result
var result int32
switch v := value.(type) {
case int:
result = int32(v)
case int8:
result = int32(v)
case int16:
result = int32(v)
case int32:
result = v
case int64:
result = int32(v)
case uint:
result = int32(v)
case uint8:
result = int32(v)
case uint16:
result = int32(v)
case uint32:
result = int32(v)
case uint64:
result = int32(v)
case float32:
result = int32(v)
case float64:
result = int32(v)
case string:
// 兼容字符串类型的值
if t, err := strconv.ParseInt(v, 10, 32); err == nil {
result = int32(t)
}
}
if result, ok := value.(int64); ok {
if result != 0 {
return int32(result)
}
}
if result, ok := value.(int); ok {
if result != 0 {
return int32(result)
}
}
// 兼容字符串类型的值
if str, ok := value.(string); ok {
if result, err := strconv.ParseInt(str, 10, 32); err == nil {
if result != 0 {
return int32(result)
}
}
if result != 0 {
return int32(result)
}
}
@@ -126,31 +137,42 @@ func GetOrDefaultInt64(dict map[string]any, key string, defaultValue int64) int6
}
if value, ok := dict[key]; ok {
if result, ok := value.(int64); ok {
if result != 0 {
return result
var result int64
switch v := value.(type) {
case int:
result = int64(v)
case int8:
result = int64(v)
case int16:
result = int64(v)
case int32:
result = int64(v)
case int64:
result = v
case uint:
result = int64(v)
case uint8:
result = int64(v)
case uint16:
result = int64(v)
case uint32:
result = int64(v)
case uint64:
result = int64(v)
case float32:
result = int64(v)
case float64:
result = int64(v)
case string:
// 兼容字符串类型的值
if t, err := strconv.ParseInt(v, 10, 32); err == nil {
result = t
}
}
if result, ok := value.(int32); ok {
if result != 0 {
return int64(result)
}
}
if result, ok := value.(int); ok {
if result != 0 {
return int64(result)
}
}
// 兼容字符串类型的值
if str, ok := value.(string); ok {
if result, err := strconv.ParseInt(str, 10, 64); err == nil {
if result != 0 {
return result
}
}
if result != 0 {
return int64(result)
}
}