package service import ( "encoding/json" "fmt" "io" "net/http" "qnc-server/app/user/cmd/api/internal/config" "strings" "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) // 将请求数据转换为JSON messageBytes, err := json.Marshal(reqParams) if err != nil { return nil, fmt.Errorf("参数序列化失败: %w", err) } // 发起HTTP请求 resp, err := http.Post(fullURL, "application/json", strings.NewReader(string(messageBytes))) 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 }