add tushare exec mod

This commit is contained in:
2026-05-01 11:19:33 +08:00
parent 82016d0bd8
commit 3c8b686980

View File

@@ -7,6 +7,7 @@ import (
"io" "io"
"net/http" "net/http"
"os" "os"
"strings"
"time" "time"
"github.com/jedib0t/go-pretty/v6/table" "github.com/jedib0t/go-pretty/v6/table"
@@ -118,6 +119,61 @@ func (c *TushareClient) Do(req TushareReq, fieldsVals []map[string]string) (*Tus
return tushareResp.Data, nil return tushareResp.Data, nil
} }
// Do 执行 Tushare API 请求
// req: 请求参数,包含 API 名称、参数等
// fieldsVals: 字段配置列表,每个元素是一个 mapkey 为字段名value 为字段中文描述
// 返回:响应数据和错误信息
func (c *TushareClient) Exec(ApiName string, fields string, Params map[string]any) (*TushareRespData, error) {
fieldsList := strings.Split(fields, ",")
if len(fieldsList) == 0 {
return nil, fmt.Errorf("#100 字段列表不能为空")
}
// 构建请求体
payload := TushareReq{
APIName: ApiName,
Token: c.Token,
Params: Params,
Fields: fieldsList,
}
// 序列化请求体为 JSON
reqBytes, err := json.Marshal(payload)
if err != nil {
return nil, fmt.Errorf("#100 请求序列化失败:%w", err)
}
// 创建 HTTP 请求
client := &http.Client{
Timeout: 30 * time.Second, // 设置 30 秒超时
}
resp, err := client.Post(c.BaseUrl, "application/json", bytes.NewReader(reqBytes))
if err != nil {
return nil, fmt.Errorf("#100 发送请求失败:%w", err)
}
defer resp.Body.Close()
// 读取响应体
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("#101 读取响应失败:%w", err)
}
// 解析响应 JSON
var tushareResp TushareResp
if err := json.Unmarshal(body, &tushareResp); err != nil {
return nil, fmt.Errorf("#101 响应解析失败:%v - %s", err, string(body))
}
// 检查响应码
if tushareResp.Code != 0 {
return nil, fmt.Errorf("#102 API 返回错误:%s", tushareResp.Msg)
}
// 设置表头信息
return tushareResp.Data, nil
}
// Map 将响应数据转换为 map 切片 // Map 将响应数据转换为 map 切片
// 每个 map 代表一行数据key 为字段名value 为对应的值 // 每个 map 代表一行数据key 为字段名value 为对应的值
func (c *TushareRespData) Map() []map[string]any { func (c *TushareRespData) Map() []map[string]any {