2025-03-20 20:32:57 +08:00
|
|
|
|
package service
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"encoding/json"
|
|
|
|
|
"fmt"
|
|
|
|
|
"io"
|
|
|
|
|
"net/http"
|
2025-03-21 15:47:11 +08:00
|
|
|
|
"net/url"
|
2025-03-20 20:32:57 +08:00
|
|
|
|
"strings"
|
2025-04-27 12:17:18 +08:00
|
|
|
|
"tyc-server/app/main/api/internal/config"
|
2025-03-20 20:32:57 +08:00
|
|
|
|
|
|
|
|
|
"github.com/tidwall/gjson"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
type TianjuService struct {
|
|
|
|
|
config config.TianjuConfig
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func NewTianjuService(c config.Config) *TianjuService {
|
|
|
|
|
return &TianjuService{
|
|
|
|
|
config: c.TianjuConfig,
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (t *TianjuService) Request(apiPath string, params map[string]interface{}) ([]byte, error) {
|
|
|
|
|
// 确保params中包含key参数
|
|
|
|
|
reqParams := make(map[string]interface{})
|
|
|
|
|
|
|
|
|
|
// 复制用户参数
|
|
|
|
|
for k, v := range params {
|
|
|
|
|
reqParams[k] = v
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 如果未提供key,则使用配置中的ApiKey
|
|
|
|
|
if _, ok := reqParams["key"]; !ok {
|
|
|
|
|
reqParams["key"] = t.config.ApiKey
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 构建完整的URL,假设BaseURL已包含https://前缀
|
|
|
|
|
fullURL := fmt.Sprintf("%s/%s/index", strings.TrimRight(t.config.BaseURL, "/"), apiPath)
|
|
|
|
|
|
2025-03-21 15:47:11 +08:00
|
|
|
|
// 构建表单数据
|
|
|
|
|
formData := url.Values{}
|
|
|
|
|
for k, v := range reqParams {
|
|
|
|
|
// 将不同类型的值转换为字符串
|
|
|
|
|
switch val := v.(type) {
|
|
|
|
|
case string:
|
|
|
|
|
formData.Add(k, val)
|
|
|
|
|
case int, int64, float64:
|
|
|
|
|
formData.Add(k, fmt.Sprintf("%v", val))
|
|
|
|
|
default:
|
|
|
|
|
// 对于复杂类型,转为JSON字符串
|
|
|
|
|
jsonBytes, err := json.Marshal(val)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, fmt.Errorf("参数值序列化失败: %w", err)
|
|
|
|
|
}
|
|
|
|
|
formData.Add(k, string(jsonBytes))
|
|
|
|
|
}
|
2025-03-20 20:32:57 +08:00
|
|
|
|
}
|
|
|
|
|
|
2025-03-21 15:47:11 +08:00
|
|
|
|
// 发起HTTP请求 - 使用表单数据
|
|
|
|
|
resp, err := http.PostForm(fullURL, formData)
|
2025-03-20 20:32:57 +08:00
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, fmt.Errorf("发送请求失败: %w", err)
|
|
|
|
|
}
|
|
|
|
|
defer resp.Body.Close()
|
|
|
|
|
|
|
|
|
|
// 读取响应体
|
|
|
|
|
body, err := io.ReadAll(resp.Body)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, fmt.Errorf("读取响应失败: %w", err)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 检查响应状态码
|
|
|
|
|
code := gjson.GetBytes(body, "code").Int()
|
|
|
|
|
if code != 200 {
|
|
|
|
|
msg := gjson.GetBytes(body, "msg").String()
|
|
|
|
|
return nil, fmt.Errorf("天聚请求失败: 状态码 %d, 信息: %s", code, msg)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 获取结果数据
|
|
|
|
|
result := gjson.GetBytes(body, "result")
|
|
|
|
|
if !result.Exists() {
|
|
|
|
|
return nil, fmt.Errorf("天聚请求result为空: %s", string(body))
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return []byte(result.Raw), nil
|
|
|
|
|
}
|