## 变更内容
### CI/CD
- 添加 GitHub Actions 工作流(test + golangci-lint)
- 添加 golangci-lint 配置,启用 errcheck/govet/staticcheck/unused/depguard
- 通过 depguard 强制 service 层不能直接导入 repository
### 错误处理修复
- 修复 CSV 写入、SSE 流式输出、随机数生成等未处理的错误
- GenerateRedeemCode() 现在返回 error
### 资源泄露修复
- 统一使用 defer func() { _ = xxx.Close() }() 模式
### 代码清理
- 移除未使用的常量
- 简化 nil map 检查
- 统一代码格式
60 lines
1.4 KiB
Go
60 lines
1.4 KiB
Go
package repository
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"net/url"
|
|
"time"
|
|
|
|
"sub2api/internal/service"
|
|
)
|
|
|
|
type claudeUsageService struct{}
|
|
|
|
func NewClaudeUsageFetcher() service.ClaudeUsageFetcher {
|
|
return &claudeUsageService{}
|
|
}
|
|
|
|
func (s *claudeUsageService) FetchUsage(ctx context.Context, accessToken, proxyURL string) (*service.ClaudeUsageResponse, error) {
|
|
transport := http.DefaultTransport.(*http.Transport).Clone()
|
|
if proxyURL != "" {
|
|
if parsedURL, err := url.Parse(proxyURL); err == nil {
|
|
transport.Proxy = http.ProxyURL(parsedURL)
|
|
}
|
|
}
|
|
|
|
client := &http.Client{
|
|
Transport: transport,
|
|
Timeout: 30 * time.Second,
|
|
}
|
|
|
|
req, err := http.NewRequestWithContext(ctx, "GET", "https://api.anthropic.com/api/oauth/usage", nil)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("create request failed: %w", err)
|
|
}
|
|
|
|
req.Header.Set("Authorization", "Bearer "+accessToken)
|
|
req.Header.Set("anthropic-beta", "oauth-2025-04-20")
|
|
|
|
resp, err := client.Do(req)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("request failed: %w", err)
|
|
}
|
|
defer func() { _ = resp.Body.Close() }()
|
|
|
|
if resp.StatusCode != http.StatusOK {
|
|
body, _ := io.ReadAll(resp.Body)
|
|
return nil, fmt.Errorf("API returned status %d: %s", resp.StatusCode, string(body))
|
|
}
|
|
|
|
var usageResp service.ClaudeUsageResponse
|
|
if err := json.NewDecoder(resp.Body).Decode(&usageResp); err != nil {
|
|
return nil, fmt.Errorf("decode response failed: %w", err)
|
|
}
|
|
|
|
return &usageResp, nil
|
|
}
|