Files
tyapi-server/internal/infrastructure/external/alicloud/alicloud_service.go
2025-08-04 17:16:38 +08:00

82 lines
1.8 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package alicloud
import (
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strings"
)
var (
ErrDatasource = errors.New("数据源异常")
ErrSystem = errors.New("系统异常")
)
// AlicloudConfig 阿里云配置
type AlicloudConfig struct {
Host string
AppCode string
}
// AlicloudService 阿里云服务
type AlicloudService struct {
config AlicloudConfig
}
// NewAlicloudService 创建阿里云服务实例
func NewAlicloudService(host, appCode string) *AlicloudService {
return &AlicloudService{
config: AlicloudConfig{
Host: host,
AppCode: appCode,
},
}
}
// CallAPI 调用阿里云API的通用方法
// path: API路径如 "api-mall/api/id_card/check"
// params: 请求参数
func (a *AlicloudService) CallAPI(path string, params map[string]interface{}) (respBytes []byte, err error) {
// 构建请求URL
reqURL := a.config.Host + "/" + path
// 构建请求参数
formData := url.Values{}
for key, value := range params {
formData.Set(key, fmt.Sprintf("%v", value))
}
// 创建HTTP请求
req, err := http.NewRequest("POST", reqURL, strings.NewReader(formData.Encode()))
if err != nil {
return nil, fmt.Errorf("%w: %s", ErrSystem, err.Error())
}
// 设置请求头
req.Header.Set("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
req.Header.Set("Authorization", "APPCODE "+a.config.AppCode)
// 发送请求
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return nil, fmt.Errorf("%w: %s", ErrSystem, err.Error())
}
defer resp.Body.Close()
// 读取响应体
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("%w: %s", ErrSystem, err.Error())
}
// 直接返回原始响应body让调用方自己处理
return body, nil
}
// GetConfig 获取配置信息
func (a *AlicloudService) GetConfig() AlicloudConfig {
return a.config
}