tyc-server/app/main/api/internal/service/tianjuService.go
2025-04-27 12:17:18 +08:00

89 lines
2.1 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 service
import (
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"tyc-server/app/main/api/internal/config"
"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)
// 构建表单数据
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))
}
}
// 发起HTTP请求 - 使用表单数据
resp, err := http.PostForm(fullURL, formData)
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
}