This commit is contained in:
2026-02-01 19:07:50 -08:00
parent af5231747a
commit 5b238919f5
7 changed files with 231 additions and 40 deletions
+86
View File
@@ -161,3 +161,89 @@ func (c *Client) CreateInviteShortLink(ctx context.Context, baseURL, inviteCode,
return link.Link, nil
}
// PeriodStats 时间段统计数据
type PeriodStats struct {
Total int `json:"total"` // 总访问量
Views []int `json:"views"` // 时间序列数据(按天/小时)
Stats StatsDetail `json:"stats"` // 详细统计
}
// StatsDetail 详细统计信息
type StatsDetail struct {
Browser []StatItem `json:"browser"` // 浏览器分布
OS []StatItem `json:"os"` // 操作系统分布
Country []StatItem `json:"country"` // 国家分布
Referrer []StatItem `json:"referrer"` // 来源分布
}
// StatItem 统计项
type StatItem struct {
Name string `json:"name"`
Value int `json:"value"`
}
// LinkStatsResponse 链接详细统计响应
type LinkStatsResponse struct {
ID string `json:"id"`
Address string `json:"address"`
Link string `json:"link"`
Target string `json:"target"`
VisitCount int `json:"visit_count"`
LastDay PeriodStats `json:"lastDay"`
LastWeek PeriodStats `json:"lastWeek"`
LastMonth PeriodStats `json:"lastMonth"`
LastYear PeriodStats `json:"lastYear"`
}
// GetLinkStats 获取链接的详细统计数据
//
// 参数:
// - ctx: 上下文
// - linkID: 链接的 UUID
//
// 返回:
// - *LinkStatsResponse: 详细统计数据
// - error: 错误信息
func (c *Client) GetLinkStats(ctx context.Context, linkID string) (*LinkStatsResponse, error) {
// 创建 HTTP 请求
url := fmt.Sprintf("%s/links/%s/stats", c.apiURL, linkID)
httpReq, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return nil, fmt.Errorf("create request failed: %w", err)
}
// 设置请求头
httpReq.Header.Set("X-API-KEY", c.apiKey)
httpReq.Header.Set("Content-Type", "application/json")
// 发送请求
resp, err := c.httpClient.Do(httpReq)
if err != nil {
return nil, fmt.Errorf("send request failed: %w", err)
}
defer resp.Body.Close()
// 读取响应体
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("read response failed: %w", err)
}
// 检查响应状态
if resp.StatusCode != http.StatusOK {
var errResp ErrorResponse
if err := json.Unmarshal(respBody, &errResp); err == nil && errResp.Error != "" {
return nil, fmt.Errorf("kutt api error: %s - %s", errResp.Error, errResp.Message)
}
return nil, fmt.Errorf("kutt api error: status %d, body: %s", resp.StatusCode, string(respBody))
}
// 解析响应
var stats LinkStatsResponse
if err := json.Unmarshal(respBody, &stats); err != nil {
return nil, fmt.Errorf("unmarshal response failed: %w", err)
}
return &stats, nil
}