refactor: re-impl sdk3rd

This commit is contained in:
Fu Diwei
2025-06-17 10:39:39 +08:00
parent 9421da2cde
commit 299a722aa9
280 changed files with 6923 additions and 4658 deletions

View File

@@ -1,48 +0,0 @@
package goedge
import (
"encoding/json"
"fmt"
"net/http"
"time"
)
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,
AccessKey: c.accessKey,
}
res, err := c.sendRequest(http.MethodPost, "/APIAccessTokenService/getAPIAccessToken", req)
if err != nil {
return err
}
resp := &getAPIAccessTokenResponse{}
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())
}
c.accessToken = resp.Data.Token
c.accessTokenExp = time.Unix(resp.Data.ExpiresAt, 0)
return nil
}
func (c *Client) UpdateSSLCert(req *UpdateSSLCertRequest) (*UpdateSSLCertResponse, error) {
if err := c.ensureAccessTokenExists(); err != nil {
return nil, err
}
resp := &UpdateSSLCertResponse{}
err := c.sendRequestWithResult(http.MethodPost, "/SSLCertService/updateSSLCert", req, resp)
return resp, err
}

View File

@@ -0,0 +1,50 @@
package goedge
import (
"context"
"net/http"
)
type UpdateSSLCertRequest struct {
SSLCertId int64 `json:"sslCertId"`
IsOn bool `json:"isOn"`
Name string `json:"name"`
Description string `json:"description"`
ServerName string `json:"serverName"`
IsCA bool `json:"isCA"`
CertData string `json:"certData"`
KeyData string `json:"keyData"`
TimeBeginAt int64 `json:"timeBeginAt"`
TimeEndAt int64 `json:"timeEndAt"`
DNSNames []string `json:"dnsNames"`
CommonNames []string `json:"commonNames"`
}
type UpdateSSLCertResponse struct {
apiResponseBase
}
func (c *Client) UpdateSSLCert(req *UpdateSSLCertRequest) (*UpdateSSLCertResponse, error) {
return c.UpdateSSLCertWithContext(context.Background(), req)
}
func (c *Client) UpdateSSLCertWithContext(ctx context.Context, req *UpdateSSLCertRequest) (*UpdateSSLCertResponse, error) {
if err := c.ensureAccessTokenExists(); err != nil {
return nil, err
}
httpreq, err := c.newRequest(http.MethodPost, "/SSLCertService/updateSSLCert")
if err != nil {
return nil, err
} else {
httpreq.SetBody(req)
httpreq.SetContext(ctx)
}
result := &UpdateSSLCertResponse{}
if _, err := c.doRequestWithResult(httpreq, result); err != nil {
return result, err
}
return result, nil
}

View File

@@ -5,6 +5,7 @@ import (
"encoding/json"
"fmt"
"net/http"
"net/url"
"strings"
"sync"
"time"
@@ -24,7 +25,26 @@ type Client struct {
client *resty.Client
}
func NewClient(serverUrl, apiRole, accessKeyId, accessKey string) *Client {
func NewClient(serverUrl, apiRole, accessKeyId, accessKey string) (*Client, error) {
if serverUrl == "" {
return nil, fmt.Errorf("sdkerr: unset serverUrl")
}
if _, err := url.Parse(serverUrl); err != nil {
return nil, fmt.Errorf("sdkerr: invalid serverUrl: %w", err)
}
if apiRole == "" {
return nil, fmt.Errorf("sdkerr: unset apiRole")
}
if apiRole != "user" && apiRole != "admin" {
return nil, fmt.Errorf("sdkerr: invalid apiRole")
}
if accessKeyId == "" {
return nil, fmt.Errorf("sdkerr: unset accessKeyId")
}
if accessKey == "" {
return nil, fmt.Errorf("sdkerr: unset accessKey")
}
client := &Client{
apiRole: apiRole,
accessKeyId: accessKeyId,
@@ -32,6 +52,8 @@ func NewClient(serverUrl, apiRole, accessKeyId, accessKey string) *Client {
}
client.client = resty.New().
SetBaseURL(strings.TrimRight(serverUrl, "/")).
SetHeader("Accept", "application/json").
SetHeader("Content-Type", "application/json").
SetHeader("User-Agent", "certimate").
SetPreRequestHook(func(c *resty.Client, req *http.Request) error {
if client.accessToken != "" {
@@ -41,62 +63,111 @@ func NewClient(serverUrl, apiRole, accessKeyId, accessKey string) *Client {
return nil
})
return client
return client, nil
}
func (c *Client) WithTimeout(timeout time.Duration) *Client {
func (c *Client) SetTimeout(timeout time.Duration) *Client {
c.client.SetTimeout(timeout)
return c
}
func (c *Client) WithTLSConfig(config *tls.Config) *Client {
func (c *Client) SetTLSConfig(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)
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")
}
resp, err := req.Execute(method, 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("goedge api error: failed to send request: %w", err)
return resp, fmt.Errorf("sdkerr: failed to send request: %w", err)
} else if resp.IsError() {
return resp, fmt.Errorf("goedge api error: unexpected status code: %d, resp: %s", resp.StatusCode(), resp.String())
return resp, fmt.Errorf("sdkerr: 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
func (c *Client) doRequestWithResult(req *resty.Request, res apiResponse) (*resty.Response, error) {
if req == nil {
return nil, fmt.Errorf("sdkerr: nil request")
}
if err := json.Unmarshal(resp.Body(), &result); err != nil {
return fmt.Errorf("goedge api error: failed to unmarshal response: %w", err)
} else if errcode := result.GetCode(); errcode != 200 {
return fmt.Errorf("goedge api error: code='%d', message='%s'", errcode, result.GetMessage())
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)
} else {
if tcode := res.GetCode(); tcode != 200 {
return resp, fmt.Errorf("sdkerr: code='%d', message='%s'", tcode, res.GetMessage())
}
}
}
return resp, nil
}
func (c *Client) ensureAccessTokenExists() error {
c.accessTokenMtx.Lock()
defer c.accessTokenMtx.Unlock()
if c.accessToken != "" && c.accessTokenExp.After(time.Now()) {
return nil
}
httpreq, err := c.newRequest(http.MethodPost, "/APIAccessTokenService/getAPIAccessToken")
if err != nil {
return err
} else {
httpreq.SetBody(map[string]string{
"type": c.apiRole,
"accessKeyId": c.accessKeyId,
"accessKey": c.accessKey,
})
}
type getAPIAccessTokenResponse struct {
apiResponseBase
Data *struct {
Token string `json:"token"`
ExpiresAt int64 `json:"expiresAt"`
} `json:"data,omitempty"`
}
result := &getAPIAccessTokenResponse{}
if _, err := c.doRequestWithResult(httpreq, result); err != nil {
return err
} else if code := result.GetCode(); code != 200 {
return fmt.Errorf("sdkerr: failed to get goedge access token: code='%d', message='%s'", code, result.GetMessage())
} else {
c.accessToken = result.Data.Token
c.accessTokenExp = time.Unix(result.Data.ExpiresAt, 0)
}
return nil

View File

@@ -1,52 +0,0 @@
package goedge
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 getAPIAccessTokenRequest struct {
Type string `json:"type"`
AccessKeyId string `json:"accessKeyId"`
AccessKey string `json:"accessKey"`
}
type getAPIAccessTokenResponse struct {
baseResponse
Data *struct {
Token string `json:"token"`
ExpiresAt int64 `json:"expiresAt"`
} `json:"data,omitempty"`
}
type UpdateSSLCertRequest struct {
SSLCertId int64 `json:"sslCertId"`
IsOn bool `json:"isOn"`
Name string `json:"name"`
Description string `json:"description"`
ServerName string `json:"serverName"`
IsCA bool `json:"isCA"`
CertData string `json:"certData"`
KeyData string `json:"keyData"`
TimeBeginAt int64 `json:"timeBeginAt"`
TimeEndAt int64 `json:"timeEndAt"`
DNSNames []string `json:"dnsNames"`
CommonNames []string `json:"commonNames"`
}
type UpdateSSLCertResponse struct {
baseResponse
}

View File

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