chore: move '/internal/pkg' to '/pkg'

This commit is contained in:
Fu Diwei
2025-06-17 15:54:21 +08:00
parent 30840bbba5
commit 205275b52d
611 changed files with 693 additions and 693 deletions

View File

@@ -0,0 +1,36 @@
package cdn
import (
"context"
"net/http"
)
type BatchUpdateCertificateConfigRequest struct {
CertificateId int64 `json:"certificateId"`
DomainNames []string `json:"domainNames"`
}
type BatchUpdateCertificateConfigResponse struct {
apiResponseBase
}
func (c *Client) BatchUpdateCertificateConfig(req *BatchUpdateCertificateConfigRequest) (*BatchUpdateCertificateConfigResponse, error) {
return c.BatchUpdateCertificateConfigWithContext(context.Background(), req)
}
func (c *Client) BatchUpdateCertificateConfigWithContext(ctx context.Context, req *BatchUpdateCertificateConfigRequest) (*BatchUpdateCertificateConfigResponse, error) {
httpreq, err := c.newRequest(http.MethodPut, "/api/config/certificate/batch")
if err != nil {
return nil, err
} else {
httpreq.SetBody(req)
httpreq.SetContext(ctx)
}
result := &BatchUpdateCertificateConfigResponse{}
if _, err := c.doRequestWithResult(httpreq, result); err != nil {
return result, err
}
return result, nil
}

View File

@@ -0,0 +1,47 @@
package cdn
import (
"fmt"
"time"
"github.com/go-resty/resty/v2"
"github.com/usual2970/certimate/pkg/sdk3rd/wangsu/openapi"
)
type Client struct {
client *openapi.Client
}
func NewClient(accessKey, secretKey string) (*Client, error) {
client, err := openapi.NewClient(accessKey, secretKey)
if err != nil {
return nil, err
}
return &Client{client: client}, nil
}
func (c *Client) SetTimeout(timeout time.Duration) *Client {
c.client.SetTimeout(timeout)
return c
}
func (c *Client) newRequest(method string, path string) (*resty.Request, error) {
return c.client.NewRequest(method, path)
}
func (c *Client) doRequest(req *resty.Request) (*resty.Response, error) {
return c.client.DoRequest(req)
}
func (c *Client) doRequestWithResult(req *resty.Request, res apiResponse) (*resty.Response, error) {
resp, err := c.client.DoRequestWithResult(req, res)
if err == nil {
if tcode := res.GetCode(); tcode != "" && tcode != "0" {
return resp, fmt.Errorf("sdkerr: api error, code='%s', message='%s'", tcode, res.GetMessage())
}
}
return resp, err
}

View File

@@ -0,0 +1,29 @@
package cdn
type apiResponse interface {
GetCode() string
GetMessage() string
}
type apiResponseBase struct {
Code *string `json:"code,omitempty"`
Message *string `json:"message,omitempty"`
}
var _ apiResponse = (*apiResponseBase)(nil)
func (r *apiResponseBase) GetCode() string {
if r.Code == nil {
return ""
}
return *r.Code
}
func (r *apiResponseBase) GetMessage() string {
if r.Message == nil {
return ""
}
return *r.Message
}

View File

@@ -0,0 +1,46 @@
package cdnpro
import (
"context"
"fmt"
"net/http"
)
type CreateCertificateRequest struct {
Timestamp int64 `json:"-"`
Name *string `json:"name,omitempty"`
Description *string `json:"description,omitempty"`
AutoRenew *string `json:"autoRenew,omitempty"`
ForceRenew *bool `json:"forceRenew,omitempty"`
NewVersion *CertificateVersionInfo `json:"newVersion,omitempty"`
}
type CreateCertificateResponse struct {
apiResponseBase
CertificateLocation string `json:"location,omitempty"`
}
func (c *Client) CreateCertificate(req *CreateCertificateRequest) (*CreateCertificateResponse, error) {
return c.CreateCertificateWithContext(context.Background(), req)
}
func (c *Client) CreateCertificateWithContext(ctx context.Context, req *CreateCertificateRequest) (*CreateCertificateResponse, error) {
httpreq, err := c.newRequest(http.MethodPost, "/cdn/certificates")
if err != nil {
return nil, err
} else {
httpreq.SetBody(req)
httpreq.SetHeader("X-CNC-Timestamp", fmt.Sprintf("%d", req.Timestamp))
httpreq.SetContext(ctx)
}
result := &CreateCertificateResponse{}
if httpresp, err := c.doRequestWithResult(httpreq, result); err != nil {
return result, err
} else {
result.CertificateLocation = httpresp.Header().Get("Location")
}
return result, nil
}

View File

@@ -0,0 +1,42 @@
package cdnpro
import (
"context"
"net/http"
)
type CreateDeploymentTaskRequest struct {
Name *string `json:"name,omitempty"`
Target *string `json:"target,omitempty"`
Actions *[]DeploymentTaskActionInfo `json:"actions,omitempty"`
Webhook *string `json:"webhook,omitempty"`
}
type CreateDeploymentTaskResponse struct {
apiResponseBase
DeploymentTaskLocation string `json:"location,omitempty"`
}
func (c *Client) CreateDeploymentTask(req *CreateDeploymentTaskRequest) (*CreateDeploymentTaskResponse, error) {
return c.CreateDeploymentTaskWithContext(context.Background(), req)
}
func (c *Client) CreateDeploymentTaskWithContext(ctx context.Context, req *CreateDeploymentTaskRequest) (*CreateDeploymentTaskResponse, error) {
httpreq, err := c.newRequest(http.MethodPost, "/cdn/deploymentTasks")
if err != nil {
return nil, err
} else {
httpreq.SetBody(req)
httpreq.SetContext(ctx)
}
result := &CreateDeploymentTaskResponse{}
if httpresp, err := c.doRequestWithResult(httpreq, result); err != nil {
return result, err
} else {
result.DeploymentTaskLocation = httpresp.Header().Get("Location")
}
return result, nil
}

View File

@@ -0,0 +1,45 @@
package cdnpro
import (
"context"
"fmt"
"net/http"
"net/url"
)
type GetDeploymentTaskDetailResponse struct {
apiResponseBase
Name string `json:"name"`
Target string `json:"target"`
Actions []DeploymentTaskActionInfo `json:"actions"`
Status string `json:"status"`
StatusDetails string `json:"statusDetails"`
SubmissionTime string `json:"submissionTime"`
FinishTime string `json:"finishTime"`
ApiRequestId string `json:"apiRequestId"`
}
func (c *Client) GetDeploymentTaskDetail(deploymentTaskId string) (*GetDeploymentTaskDetailResponse, error) {
return c.GetDeploymentTaskDetailWithContext(context.Background(), deploymentTaskId)
}
func (c *Client) GetDeploymentTaskDetailWithContext(ctx context.Context, deploymentTaskId string) (*GetDeploymentTaskDetailResponse, error) {
if deploymentTaskId == "" {
return nil, fmt.Errorf("sdkerr: unset deploymentTaskId")
}
httpreq, err := c.newRequest(http.MethodGet, fmt.Sprintf("/cdn/deploymentTasks/%s", url.PathEscape(deploymentTaskId)))
if err != nil {
return nil, err
} else {
httpreq.SetContext(ctx)
}
result := &GetDeploymentTaskDetailResponse{}
if _, err := c.doRequestWithResult(httpreq, result); err != nil {
return result, err
}
return result, nil
}

View File

@@ -0,0 +1,40 @@
package cdnpro
import (
"context"
"fmt"
"net/http"
"net/url"
)
type GetHostnameDetailResponse struct {
apiResponseBase
Hostname string `json:"hostname"`
PropertyInProduction *HostnamePropertyInfo `json:"propertyInProduction,omitempty"`
PropertyInStaging *HostnamePropertyInfo `json:"propertyInStaging,omitempty"`
}
func (c *Client) GetHostnameDetail(hostname string) (*GetHostnameDetailResponse, error) {
return c.GetHostnameDetailWithContext(context.Background(), hostname)
}
func (c *Client) GetHostnameDetailWithContext(ctx context.Context, hostname string) (*GetHostnameDetailResponse, error) {
if hostname == "" {
return nil, fmt.Errorf("sdkerr: unset hostname")
}
httpreq, err := c.newRequest(http.MethodGet, fmt.Sprintf("/cdn/hostnames/%s", url.PathEscape(hostname)))
if err != nil {
return nil, err
} else {
httpreq.SetContext(ctx)
}
result := &GetHostnameDetailResponse{}
if _, err := c.doRequestWithResult(httpreq, result); err != nil {
return result, err
}
return result, nil
}

View File

@@ -0,0 +1,51 @@
package cdnpro
import (
"context"
"fmt"
"net/http"
"net/url"
)
type UpdateCertificateRequest struct {
Timestamp int64 `json:"-"`
Name *string `json:"name,omitempty"`
Description *string `json:"description,omitempty"`
AutoRenew *string `json:"autoRenew,omitempty"`
ForceRenew *bool `json:"forceRenew,omitempty"`
NewVersion *CertificateVersionInfo `json:"newVersion,omitempty"`
}
type UpdateCertificateResponse struct {
apiResponseBase
CertificateLocation string `json:"location,omitempty"`
}
func (c *Client) UpdateCertificate(certificateId string, req *UpdateCertificateRequest) (*UpdateCertificateResponse, error) {
return c.UpdateCertificateWithContext(context.Background(), certificateId, req)
}
func (c *Client) UpdateCertificateWithContext(ctx context.Context, certificateId string, req *UpdateCertificateRequest) (*UpdateCertificateResponse, error) {
if certificateId == "" {
return nil, fmt.Errorf("sdkerr: unset certificateId")
}
httpreq, err := c.newRequest(http.MethodPatch, fmt.Sprintf("/cdn/certificates/%s", url.PathEscape(certificateId)))
if err != nil {
return nil, err
} else {
httpreq.SetBody(req)
httpreq.SetHeader("X-CNC-Timestamp", fmt.Sprintf("%d", req.Timestamp))
httpreq.SetContext(ctx)
}
result := &UpdateCertificateResponse{}
if httpresp, err := c.doRequestWithResult(httpreq, result); err != nil {
return result, err
} else {
result.CertificateLocation = httpresp.Header().Get("Location")
}
return result, nil
}

View File

@@ -0,0 +1,39 @@
package cdnpro
import (
"time"
"github.com/go-resty/resty/v2"
"github.com/usual2970/certimate/pkg/sdk3rd/wangsu/openapi"
)
type Client struct {
client *openapi.Client
}
func NewClient(accessKey, secretKey string) (*Client, error) {
client, err := openapi.NewClient(accessKey, secretKey)
if err != nil {
return nil, err
}
return &Client{client: client}, nil
}
func (c *Client) SetTimeout(timeout time.Duration) *Client {
c.client.SetTimeout(timeout)
return c
}
func (c *Client) newRequest(method string, path string) (*resty.Request, error) {
return c.client.NewRequest(method, path)
}
func (c *Client) doRequest(req *resty.Request) (*resty.Response, error) {
return c.client.DoRequest(req)
}
func (c *Client) doRequestWithResult(req *resty.Request, res apiResponse) (*resty.Response, error) {
return c.client.DoRequestWithResult(req, res)
}

View File

@@ -0,0 +1,61 @@
package cdnpro
type apiResponse interface {
GetCode() string
GetMessage() string
}
type apiResponseBase struct {
Code *string `json:"code,omitempty"`
Message *string `json:"message,omitempty"`
}
var _ apiResponse = (*apiResponseBase)(nil)
func (r *apiResponseBase) GetCode() string {
if r.Code == nil {
return ""
}
return *r.Code
}
func (r *apiResponseBase) GetMessage() string {
if r.Message == nil {
return ""
}
return *r.Message
}
type CertificateVersionInfo struct {
Comments *string `json:"comments,omitempty"`
PrivateKey *string `json:"privateKey,omitempty"`
Certificate *string `json:"certificate,omitempty"`
ChainCert *string `json:"chainCert,omitempty"`
IdentificationInfo *CertificateVersionIdentificationInfo `json:"identificationInfo,omitempty"`
}
type CertificateVersionIdentificationInfo struct {
Country *string `json:"country,omitempty"`
State *string `json:"state,omitempty"`
City *string `json:"city,omitempty"`
Company *string `json:"company,omitempty"`
Department *string `json:"department,omitempty"`
CommonName *string `json:"commonName,omitempty"`
Email *string `json:"email,omitempty"`
SubjectAlternativeNames *[]string `json:"subjectAlternativeNames,omitempty"`
}
type HostnamePropertyInfo struct {
PropertyId string `json:"propertyId"`
Version int32 `json:"version"`
CertificateId *string `json:"certificateId,omitempty"`
}
type DeploymentTaskActionInfo struct {
Action *string `json:"action,omitempty"`
PropertyId *string `json:"propertyId,omitempty"`
CertificateId *string `json:"certificateId,omitempty"`
Version *int32 `json:"version,omitempty"`
}

View File

@@ -0,0 +1,42 @@
package certificate
import (
"context"
"net/http"
)
type CreateCertificateRequest struct {
Name *string `json:"name,omitempty"`
Certificate *string `json:"certificate,omitempty"`
PrivateKey *string `json:"privateKey,omitempty"`
Comment *string `json:"comment,omitempty" `
}
type CreateCertificateResponse struct {
apiResponseBase
CertificateLocation string `json:"location,omitempty"`
}
func (c *Client) CreateCertificate(req *CreateCertificateRequest) (*CreateCertificateResponse, error) {
return c.CreateCertificateWithContext(context.Background(), req)
}
func (c *Client) CreateCertificateWithContext(ctx context.Context, req *CreateCertificateRequest) (*CreateCertificateResponse, error) {
httpreq, err := c.newRequest(http.MethodPost, "/api/certificate")
if err != nil {
return nil, err
} else {
httpreq.SetBody(req)
httpreq.SetContext(ctx)
}
result := &CreateCertificateResponse{}
if httpresp, err := c.doRequestWithResult(httpreq, result); err != nil {
return result, err
} else {
result.CertificateLocation = httpresp.Header().Get("Location")
}
return result, nil
}

View File

@@ -0,0 +1,32 @@
package certificate
import (
"context"
"net/http"
)
type ListCertificatesResponse struct {
apiResponseBase
Certificates []*CertificateRecord `json:"ssl-certificates,omitempty"`
}
func (c *Client) ListCertificates() (*ListCertificatesResponse, error) {
return c.ListCertificatesWithContext(context.Background())
}
func (c *Client) ListCertificatesWithContext(ctx context.Context) (*ListCertificatesResponse, error) {
httpreq, err := c.newRequest(http.MethodGet, "/api/ssl/certificate")
if err != nil {
return nil, err
} else {
httpreq.SetContext(ctx)
}
result := &ListCertificatesResponse{}
if _, err := c.doRequestWithResult(httpreq, result); err != nil {
return result, err
}
return result, nil
}

View File

@@ -0,0 +1,44 @@
package certificate
import (
"context"
"fmt"
"net/http"
"net/url"
)
type UpdateCertificateRequest struct {
Name *string `json:"name,omitempty"`
Certificate *string `json:"certificate,omitempty"`
PrivateKey *string `json:"privateKey,omitempty"`
Comment *string `json:"comment,omitempty" `
}
type UpdateCertificateResponse struct {
apiResponseBase
}
func (c *Client) UpdateCertificate(certificateId string, req *UpdateCertificateRequest) (*UpdateCertificateResponse, error) {
return c.UpdateCertificateWithContext(context.Background(), certificateId, req)
}
func (c *Client) UpdateCertificateWithContext(ctx context.Context, certificateId string, req *UpdateCertificateRequest) (*UpdateCertificateResponse, error) {
if certificateId == "" {
return nil, fmt.Errorf("sdkerr: unset certificateId")
}
httpreq, err := c.newRequest(http.MethodPut, fmt.Sprintf("/api/certificate/%s", url.PathEscape(certificateId)))
if err != nil {
return nil, err
} else {
httpreq.SetBody(req)
httpreq.SetContext(ctx)
}
result := &UpdateCertificateResponse{}
if _, err := c.doRequestWithResult(httpreq, result); err != nil {
return result, err
}
return result, nil
}

View File

@@ -0,0 +1,39 @@
package certificate
import (
"time"
"github.com/go-resty/resty/v2"
"github.com/usual2970/certimate/pkg/sdk3rd/wangsu/openapi"
)
type Client struct {
client *openapi.Client
}
func NewClient(accessKey, secretKey string) (*Client, error) {
client, err := openapi.NewClient(accessKey, secretKey)
if err != nil {
return nil, err
}
return &Client{client: client}, nil
}
func (c *Client) SetTimeout(timeout time.Duration) *Client {
c.client.SetTimeout(timeout)
return c
}
func (c *Client) newRequest(method string, path string) (*resty.Request, error) {
return c.client.NewRequest(method, path)
}
func (c *Client) doRequest(req *resty.Request) (*resty.Response, error) {
return c.client.DoRequest(req)
}
func (c *Client) doRequestWithResult(req *resty.Request, res apiResponse) (*resty.Response, error) {
return c.client.DoRequestWithResult(req, res)
}

View File

@@ -0,0 +1,38 @@
package certificate
type apiResponse interface {
GetCode() string
GetMessage() string
}
type apiResponseBase struct {
Code *string `json:"code,omitempty"`
Message *string `json:"message,omitempty"`
}
var _ apiResponse = (*apiResponseBase)(nil)
func (r *apiResponseBase) GetCode() string {
if r.Code == nil {
return ""
}
return *r.Code
}
func (r *apiResponseBase) GetMessage() string {
if r.Message == nil {
return ""
}
return *r.Message
}
type CertificateRecord struct {
CertificateId string `json:"certificate-id"`
Name string `json:"name"`
Comment string `json:"comment"`
ValidityFrom string `json:"certificate-validity-from"`
ValidityTo string `json:"certificate-validity-to"`
Serial string `json:"certificate-serial"`
}

View File

@@ -0,0 +1,191 @@
package openapi
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"github.com/go-resty/resty/v2"
)
type Client struct {
accessKey string
secretKey string
client *resty.Client
}
func NewClient(accessKey, secretKey string) (*Client, error) {
if accessKey == "" {
return nil, fmt.Errorf("sdkerr: unset accessKey")
}
if secretKey == "" {
return nil, fmt.Errorf("sdkerr: unset secretKey")
}
client := resty.New().
SetBaseURL("https://open.chinanetcenter.com").
SetHeader("Accept", "application/json").
SetHeader("Content-Type", "application/json").
SetHeader("Host", "open.chinanetcenter.com").
SetHeader("User-Agent", "certimate").
SetPreRequestHook(func(c *resty.Client, req *http.Request) error {
// Step 1: Get request method
method := req.Method
method = strings.ToUpper(method)
// Step 2: Get request path
path := "/"
if req.URL != nil {
path = req.URL.Path
}
// Step 3: Get unencoded query string
queryString := ""
if method != http.MethodPost && req.URL != nil {
queryString = req.URL.RawQuery
s, err := url.QueryUnescape(queryString)
if err != nil {
return err
}
queryString = s
}
// Step 4: Get canonical headers & signed headers
canonicalHeaders := "" +
"content-type:" + strings.TrimSpace(strings.ToLower(req.Header.Get("Content-Type"))) + "\n" +
"host:" + strings.TrimSpace(strings.ToLower(req.Header.Get("Host"))) + "\n"
signedHeaders := "content-type;host"
// Step 5: Get request payload
payload := ""
if method != http.MethodGet && req.Body != nil {
reader, err := req.GetBody()
if err != nil {
return err
}
defer reader.Close()
payloadb, err := io.ReadAll(reader)
if err != nil {
return err
}
payload = string(payloadb)
}
hashedPayload := sha256.Sum256([]byte(payload))
hashedPayloadHex := strings.ToLower(hex.EncodeToString(hashedPayload[:]))
// Step 6: Get timestamp
var reqtime time.Time
timestampString := req.Header.Get("X-CNC-Timestamp")
if timestampString == "" {
reqtime = time.Now().UTC()
timestampString = fmt.Sprintf("%d", reqtime.Unix())
} else {
timestamp, err := strconv.ParseInt(timestampString, 10, 64)
if err != nil {
return err
}
reqtime = time.Unix(timestamp, 0).UTC()
}
// Step 7: Get canonical request string
canonicalRequest := fmt.Sprintf("%s\n%s\n%s\n%s\n%s\n%s", method, path, queryString, canonicalHeaders, signedHeaders, hashedPayloadHex)
hashedCanonicalRequest := sha256.Sum256([]byte(canonicalRequest))
hashedCanonicalRequestHex := strings.ToLower(hex.EncodeToString(hashedCanonicalRequest[:]))
// Step 8: String to sign
const SignAlgorithmHeader = "CNC-HMAC-SHA256"
stringToSign := fmt.Sprintf("%s\n%s\n%s", SignAlgorithmHeader, timestampString, hashedCanonicalRequestHex)
hmac := hmac.New(sha256.New, []byte(secretKey))
hmac.Write([]byte(stringToSign))
sign := hmac.Sum(nil)
signHex := strings.ToLower(hex.EncodeToString(sign))
// Step 9: Add headers to request
req.Header.Set("X-CNC-AccessKey", accessKey)
req.Header.Set("X-CNC-Timestamp", timestampString)
req.Header.Set("X-CNC-Auth-Method", "AKSK")
req.Header.Set("Authorization", fmt.Sprintf("%s Credential=%s, SignedHeaders=%s, Signature=%s", SignAlgorithmHeader, accessKey, signedHeaders, signHex))
req.Header.Set("Date", reqtime.Format("Mon, 02 Jan 2006 15:04:05 GMT"))
return nil
})
return &Client{
accessKey: accessKey,
secretKey: secretKey,
client: client,
}, nil
}
func (c *Client) SetTimeout(timeout time.Duration) *Client {
c.client.SetTimeout(timeout)
return c
}
func (c *Client) NewRequest(method string, path string) (*resty.Request, error) {
if method == "" {
return nil, fmt.Errorf("sdkerr: unset method")
}
if path == "" {
return nil, fmt.Errorf("sdkerr: unset path")
}
req := c.client.R()
req.Method = method
req.URL = path
return req, nil
}
func (c *Client) DoRequest(req *resty.Request) (*resty.Response, error) {
if req == nil {
return nil, fmt.Errorf("sdkerr: nil request")
}
// WARN:
// PLEASE DO NOT USE `req.SetResult` or `req.SetError` HERE! USE `doRequestWithResult` INSTEAD.
resp, err := req.Send()
if err != nil {
return resp, fmt.Errorf("sdkerr: failed to send request: %w", err)
} else if resp.IsError() {
return resp, fmt.Errorf("sdkerr: unexpected status code: %d, resp: %s", resp.StatusCode(), resp.String())
}
return resp, nil
}
func (c *Client) DoRequestWithResult(req *resty.Request, res any) (*resty.Response, error) {
if req == nil {
return nil, fmt.Errorf("sdkerr: nil request")
}
resp, err := c.DoRequest(req)
if err != nil {
if resp != nil {
json.Unmarshal(resp.Body(), &res)
}
return resp, err
}
if len(resp.Body()) != 0 {
if err := json.Unmarshal(resp.Body(), &res); err != nil {
return resp, fmt.Errorf("sdkerr: failed to unmarshal response: %w", err)
}
}
return resp, nil
}