new
This commit is contained in:
88
app/main/api/internal/service/tianjuService.go
Normal file
88
app/main/api/internal/service/tianjuService.go
Normal file
@@ -0,0 +1,88 @@
|
||||
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
|
||||
}
|
||||
Reference in New Issue
Block a user