From 1e1f3c0c74f8ea26bd51615a801b0d177ea4f92f Mon Sep 17 00:00:00 2001 From: Forest Date: Sat, 20 Dec 2025 16:19:40 +0800 Subject: [PATCH] =?UTF-8?q?ci(backend):=20=E6=B7=BB=E5=8A=A0=20gofmt=20?= =?UTF-8?q?=E9=85=8D=E7=BD=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/.golangci.yml | 15 +++++- .../internal/handler/admin/account_handler.go | 38 +++++++-------- .../handler/admin/dashboard_handler.go | 4 +- .../internal/handler/admin/usage_handler.go | 2 +- backend/internal/handler/usage_handler.go | 4 +- backend/internal/model/account.go | 8 ++-- backend/internal/pkg/response/response.go | 24 +++++----- backend/internal/repository/account_repo.go | 8 ++-- backend/internal/repository/billing_cache.go | 2 +- .../repository/claude_oauth_service.go | 4 +- .../internal/repository/redeem_code_repo.go | 2 +- .../repository/user_subscription_repo.go | 18 +++---- backend/internal/service/account_service.go | 34 ++++++------- .../internal/service/account_test_service.go | 16 +++---- backend/internal/service/admin_service.go | 14 +++--- backend/internal/service/auth_service.go | 2 +- backend/internal/service/billing_service.go | 4 +- backend/internal/service/gateway_service.go | 48 +++++++++---------- backend/internal/service/group_service.go | 4 +- backend/internal/service/identity_service.go | 4 +- backend/internal/service/pricing_service.go | 4 +- backend/internal/service/redeem_service.go | 4 +- backend/internal/service/token_refresher.go | 6 +-- backend/internal/service/usage_service.go | 6 +-- 24 files changed, 144 insertions(+), 131 deletions(-) diff --git a/backend/.golangci.yml b/backend/.golangci.yml index 6dc8faac..415a02ac 100644 --- a/backend/.golangci.yml +++ b/backend/.golangci.yml @@ -571,4 +571,17 @@ linters: formatters: enable: - - gofmt \ No newline at end of file + - gofmt + settings: + gofmt: + # Simplify code: gofmt with `-s` option. + # Default: true + simplify: false + # Apply the rewrite rules to the source before reformatting. + # https://pkg.go.dev/cmd/gofmt + # Default: [] + rewrite-rules: + - pattern: 'interface{}' + replacement: 'any' + - pattern: 'a[b:len(a)]' + replacement: 'a[b:]' \ No newline at end of file diff --git a/backend/internal/handler/admin/account_handler.go b/backend/internal/handler/admin/account_handler.go index c46d15df..4ab10362 100644 --- a/backend/internal/handler/admin/account_handler.go +++ b/backend/internal/handler/admin/account_handler.go @@ -44,29 +44,29 @@ func NewAccountHandler(adminService service.AdminService, oauthService *service. // CreateAccountRequest represents create account request type CreateAccountRequest struct { - Name string `json:"name" binding:"required"` - Platform string `json:"platform" binding:"required"` - Type string `json:"type" binding:"required,oneof=oauth setup-token apikey"` - Credentials map[string]interface{} `json:"credentials" binding:"required"` - Extra map[string]interface{} `json:"extra"` - ProxyID *int64 `json:"proxy_id"` - Concurrency int `json:"concurrency"` - Priority int `json:"priority"` - GroupIDs []int64 `json:"group_ids"` + Name string `json:"name" binding:"required"` + Platform string `json:"platform" binding:"required"` + Type string `json:"type" binding:"required,oneof=oauth setup-token apikey"` + Credentials map[string]any `json:"credentials" binding:"required"` + Extra map[string]any `json:"extra"` + ProxyID *int64 `json:"proxy_id"` + Concurrency int `json:"concurrency"` + Priority int `json:"priority"` + GroupIDs []int64 `json:"group_ids"` } // UpdateAccountRequest represents update account request // 使用指针类型来区分"未提供"和"设置为0" type UpdateAccountRequest struct { - Name string `json:"name"` - Type string `json:"type" binding:"omitempty,oneof=oauth setup-token apikey"` - Credentials map[string]interface{} `json:"credentials"` - Extra map[string]interface{} `json:"extra"` - ProxyID *int64 `json:"proxy_id"` - Concurrency *int `json:"concurrency"` - Priority *int `json:"priority"` - Status string `json:"status" binding:"omitempty,oneof=active inactive"` - GroupIDs *[]int64 `json:"group_ids"` + Name string `json:"name"` + Type string `json:"type" binding:"omitempty,oneof=oauth setup-token apikey"` + Credentials map[string]any `json:"credentials"` + Extra map[string]any `json:"extra"` + ProxyID *int64 `json:"proxy_id"` + Concurrency *int `json:"concurrency"` + Priority *int `json:"priority"` + Status string `json:"status" binding:"omitempty,oneof=active inactive"` + GroupIDs *[]int64 `json:"group_ids"` } // List handles listing all accounts with pagination @@ -240,7 +240,7 @@ func (h *AccountHandler) Refresh(c *gin.Context) { } // Copy existing credentials to preserve non-token settings (e.g., intercept_warmup_requests) - newCredentials := make(map[string]interface{}) + newCredentials := make(map[string]any) for k, v := range account.Credentials { newCredentials[k] = v } diff --git a/backend/internal/handler/admin/dashboard_handler.go b/backend/internal/handler/admin/dashboard_handler.go index 5ca56231..2fd4f268 100644 --- a/backend/internal/handler/admin/dashboard_handler.go +++ b/backend/internal/handler/admin/dashboard_handler.go @@ -255,7 +255,7 @@ func (h *DashboardHandler) GetBatchUsersUsage(c *gin.Context) { } if len(req.UserIDs) == 0 { - response.Success(c, gin.H{"stats": map[string]interface{}{}}) + response.Success(c, gin.H{"stats": map[string]any{}}) return } @@ -283,7 +283,7 @@ func (h *DashboardHandler) GetBatchApiKeysUsage(c *gin.Context) { } if len(req.ApiKeyIDs) == 0 { - response.Success(c, gin.H{"stats": map[string]interface{}{}}) + response.Success(c, gin.H{"stats": map[string]any{}}) return } diff --git a/backend/internal/handler/admin/usage_handler.go b/backend/internal/handler/admin/usage_handler.go index 9241abb6..00501a52 100644 --- a/backend/internal/handler/admin/usage_handler.go +++ b/backend/internal/handler/admin/usage_handler.go @@ -193,7 +193,7 @@ func (h *UsageHandler) Stats(c *gin.Context) { func (h *UsageHandler) SearchUsers(c *gin.Context) { keyword := c.Query("q") if keyword == "" { - response.Success(c, []interface{}{}) + response.Success(c, []any{}) return } diff --git a/backend/internal/handler/usage_handler.go b/backend/internal/handler/usage_handler.go index 26bd8da4..3738ca28 100644 --- a/backend/internal/handler/usage_handler.go +++ b/backend/internal/handler/usage_handler.go @@ -358,7 +358,7 @@ func (h *UsageHandler) DashboardApiKeysUsage(c *gin.Context) { } if len(req.ApiKeyIDs) == 0 { - response.Success(c, gin.H{"stats": map[string]interface{}{}}) + response.Success(c, gin.H{"stats": map[string]any{}}) return } @@ -383,7 +383,7 @@ func (h *UsageHandler) DashboardApiKeysUsage(c *gin.Context) { } if len(validApiKeyIDs) == 0 { - response.Success(c, gin.H{"stats": map[string]interface{}{}}) + response.Success(c, gin.H{"stats": map[string]any{}}) return } diff --git a/backend/internal/model/account.go b/backend/internal/model/account.go index 22d2e7c8..2bb7079f 100644 --- a/backend/internal/model/account.go +++ b/backend/internal/model/account.go @@ -10,7 +10,7 @@ import ( ) // JSONB 用于存储JSONB数据 -type JSONB map[string]interface{} +type JSONB map[string]any func (j JSONB) Value() (driver.Value, error) { if j == nil { @@ -19,7 +19,7 @@ func (j JSONB) Value() (driver.Value, error) { return json.Marshal(j) } -func (j *JSONB) Scan(value interface{}) error { +func (j *JSONB) Scan(value any) error { if value == nil { *j = nil return nil @@ -145,7 +145,7 @@ func (a *Account) GetModelMapping() map[string]string { return nil } // 处理map[string]interface{}类型 - if m, ok := raw.(map[string]interface{}); ok { + if m, ok := raw.(map[string]any); ok { result := make(map[string]string) for k, v := range m { if s, ok := v.(string); ok { @@ -231,7 +231,7 @@ func (a *Account) GetCustomErrorCodes() []int { return nil } // 处理 []interface{} 类型(JSON反序列化后的格式) - if arr, ok := raw.([]interface{}); ok { + if arr, ok := raw.([]any); ok { result := make([]int, 0, len(arr)) for _, v := range arr { // JSON 数字默认解析为 float64 diff --git a/backend/internal/pkg/response/response.go b/backend/internal/pkg/response/response.go index 0739bb25..6bbfee4c 100644 --- a/backend/internal/pkg/response/response.go +++ b/backend/internal/pkg/response/response.go @@ -9,22 +9,22 @@ import ( // Response 标准API响应格式 type Response struct { - Code int `json:"code"` - Message string `json:"message"` - Data interface{} `json:"data,omitempty"` + Code int `json:"code"` + Message string `json:"message"` + Data any `json:"data,omitempty"` } // PaginatedData 分页数据格式(匹配前端期望) type PaginatedData struct { - Items interface{} `json:"items"` - Total int64 `json:"total"` - Page int `json:"page"` - PageSize int `json:"page_size"` - Pages int `json:"pages"` + Items any `json:"items"` + Total int64 `json:"total"` + Page int `json:"page"` + PageSize int `json:"page_size"` + Pages int `json:"pages"` } // Success 返回成功响应 -func Success(c *gin.Context, data interface{}) { +func Success(c *gin.Context, data any) { c.JSON(http.StatusOK, Response{ Code: 0, Message: "success", @@ -33,7 +33,7 @@ func Success(c *gin.Context, data interface{}) { } // Created 返回创建成功响应 -func Created(c *gin.Context, data interface{}) { +func Created(c *gin.Context, data any) { c.JSON(http.StatusCreated, Response{ Code: 0, Message: "success", @@ -75,7 +75,7 @@ func InternalError(c *gin.Context, message string) { } // Paginated 返回分页数据 -func Paginated(c *gin.Context, items interface{}, total int64, page, pageSize int) { +func Paginated(c *gin.Context, items any, total int64, page, pageSize int) { pages := int(math.Ceil(float64(total) / float64(pageSize))) if pages < 1 { pages = 1 @@ -99,7 +99,7 @@ type PaginationResult struct { } // PaginatedWithResult 使用PaginationResult返回分页数据 -func PaginatedWithResult(c *gin.Context, items interface{}, pagination *PaginationResult) { +func PaginatedWithResult(c *gin.Context, items any, pagination *PaginationResult) { if pagination == nil { Success(c, PaginatedData{ Items: items, diff --git a/backend/internal/repository/account_repo.go b/backend/internal/repository/account_repo.go index a746d412..2a1317c9 100644 --- a/backend/internal/repository/account_repo.go +++ b/backend/internal/repository/account_repo.go @@ -131,7 +131,7 @@ func (r *AccountRepository) UpdateLastUsed(ctx context.Context, id int64) error func (r *AccountRepository) SetError(ctx context.Context, id int64, errorMsg string) error { return r.db.WithContext(ctx).Model(&model.Account{}).Where("id = ?", id). - Updates(map[string]interface{}{ + Updates(map[string]any{ "status": model.StatusError, "error_message": errorMsg, }).Error @@ -226,7 +226,7 @@ func (r *AccountRepository) ListSchedulableByGroupID(ctx context.Context, groupI func (r *AccountRepository) SetRateLimited(ctx context.Context, id int64, resetAt time.Time) error { now := time.Now() return r.db.WithContext(ctx).Model(&model.Account{}).Where("id = ?", id). - Updates(map[string]interface{}{ + Updates(map[string]any{ "rate_limited_at": now, "rate_limit_reset_at": resetAt, }).Error @@ -241,7 +241,7 @@ func (r *AccountRepository) SetOverloaded(ctx context.Context, id int64, until t // ClearRateLimit 清除账号的限流状态 func (r *AccountRepository) ClearRateLimit(ctx context.Context, id int64) error { return r.db.WithContext(ctx).Model(&model.Account{}).Where("id = ?", id). - Updates(map[string]interface{}{ + Updates(map[string]any{ "rate_limited_at": nil, "rate_limit_reset_at": nil, "overload_until": nil, @@ -250,7 +250,7 @@ func (r *AccountRepository) ClearRateLimit(ctx context.Context, id int64) error // UpdateSessionWindow 更新账号的5小时时间窗口信息 func (r *AccountRepository) UpdateSessionWindow(ctx context.Context, id int64, start, end *time.Time, status string) error { - updates := map[string]interface{}{ + updates := map[string]any{ "session_window_status": status, } if start != nil { diff --git a/backend/internal/repository/billing_cache.go b/backend/internal/repository/billing_cache.go index 99ec2b76..c5b4e029 100644 --- a/backend/internal/repository/billing_cache.go +++ b/backend/internal/repository/billing_cache.go @@ -143,7 +143,7 @@ func (c *billingCache) SetSubscriptionCache(ctx context.Context, userID, groupID key := fmt.Sprintf("%s%d:%d", billingSubKeyPrefix, userID, groupID) - fields := map[string]interface{}{ + fields := map[string]any{ subFieldStatus: data.Status, subFieldExpiresAt: data.ExpiresAt.Unix(), subFieldDailyUsage: data.DailyUsage, diff --git a/backend/internal/repository/claude_oauth_service.go b/backend/internal/repository/claude_oauth_service.go index ab0dee88..8cc4bce2 100644 --- a/backend/internal/repository/claude_oauth_service.go +++ b/backend/internal/repository/claude_oauth_service.go @@ -64,7 +64,7 @@ func (s *claudeOAuthService) GetAuthorizationCode(ctx context.Context, sessionKe authURL := fmt.Sprintf("https://claude.ai/v1/oauth/%s/authorize", orgUUID) - reqBody := map[string]interface{}{ + reqBody := map[string]any{ "response_type": "code", "client_id": oauth.ClientID, "organization_uuid": orgUUID, @@ -155,7 +155,7 @@ func (s *claudeOAuthService) ExchangeCodeForToken(ctx context.Context, code, cod } } - reqBody := map[string]interface{}{ + reqBody := map[string]any{ "code": authCode, "grant_type": "authorization_code", "client_id": oauth.ClientID, diff --git a/backend/internal/repository/redeem_code_repo.go b/backend/internal/repository/redeem_code_repo.go index f971a9f3..dc4bada3 100644 --- a/backend/internal/repository/redeem_code_repo.go +++ b/backend/internal/repository/redeem_code_repo.go @@ -99,7 +99,7 @@ func (r *RedeemCodeRepository) Use(ctx context.Context, id, userID int64) error now := time.Now() result := r.db.WithContext(ctx).Model(&model.RedeemCode{}). Where("id = ? AND status = ?", id, model.StatusUnused). - Updates(map[string]interface{}{ + Updates(map[string]any{ "status": model.StatusUsed, "used_by": userID, "used_at": now, diff --git a/backend/internal/repository/user_subscription_repo.go b/backend/internal/repository/user_subscription_repo.go index 7f2b74e4..e13ef835 100644 --- a/backend/internal/repository/user_subscription_repo.go +++ b/backend/internal/repository/user_subscription_repo.go @@ -185,7 +185,7 @@ func (r *UserSubscriptionRepository) List(ctx context.Context, params pagination func (r *UserSubscriptionRepository) IncrementUsage(ctx context.Context, id int64, costUSD float64) error { return r.db.WithContext(ctx).Model(&model.UserSubscription{}). Where("id = ?", id). - Updates(map[string]interface{}{ + Updates(map[string]any{ "daily_usage_usd": gorm.Expr("daily_usage_usd + ?", costUSD), "weekly_usage_usd": gorm.Expr("weekly_usage_usd + ?", costUSD), "monthly_usage_usd": gorm.Expr("monthly_usage_usd + ?", costUSD), @@ -197,7 +197,7 @@ func (r *UserSubscriptionRepository) IncrementUsage(ctx context.Context, id int6 func (r *UserSubscriptionRepository) ResetDailyUsage(ctx context.Context, id int64, newWindowStart time.Time) error { return r.db.WithContext(ctx).Model(&model.UserSubscription{}). Where("id = ?", id). - Updates(map[string]interface{}{ + Updates(map[string]any{ "daily_usage_usd": 0, "daily_window_start": newWindowStart, "updated_at": time.Now(), @@ -208,7 +208,7 @@ func (r *UserSubscriptionRepository) ResetDailyUsage(ctx context.Context, id int func (r *UserSubscriptionRepository) ResetWeeklyUsage(ctx context.Context, id int64, newWindowStart time.Time) error { return r.db.WithContext(ctx).Model(&model.UserSubscription{}). Where("id = ?", id). - Updates(map[string]interface{}{ + Updates(map[string]any{ "weekly_usage_usd": 0, "weekly_window_start": newWindowStart, "updated_at": time.Now(), @@ -219,7 +219,7 @@ func (r *UserSubscriptionRepository) ResetWeeklyUsage(ctx context.Context, id in func (r *UserSubscriptionRepository) ResetMonthlyUsage(ctx context.Context, id int64, newWindowStart time.Time) error { return r.db.WithContext(ctx).Model(&model.UserSubscription{}). Where("id = ?", id). - Updates(map[string]interface{}{ + Updates(map[string]any{ "monthly_usage_usd": 0, "monthly_window_start": newWindowStart, "updated_at": time.Now(), @@ -230,7 +230,7 @@ func (r *UserSubscriptionRepository) ResetMonthlyUsage(ctx context.Context, id i func (r *UserSubscriptionRepository) ActivateWindows(ctx context.Context, id int64, activateTime time.Time) error { return r.db.WithContext(ctx).Model(&model.UserSubscription{}). Where("id = ?", id). - Updates(map[string]interface{}{ + Updates(map[string]any{ "daily_window_start": activateTime, "weekly_window_start": activateTime, "monthly_window_start": activateTime, @@ -242,7 +242,7 @@ func (r *UserSubscriptionRepository) ActivateWindows(ctx context.Context, id int func (r *UserSubscriptionRepository) UpdateStatus(ctx context.Context, id int64, status string) error { return r.db.WithContext(ctx).Model(&model.UserSubscription{}). Where("id = ?", id). - Updates(map[string]interface{}{ + Updates(map[string]any{ "status": status, "updated_at": time.Now(), }).Error @@ -252,7 +252,7 @@ func (r *UserSubscriptionRepository) UpdateStatus(ctx context.Context, id int64, func (r *UserSubscriptionRepository) ExtendExpiry(ctx context.Context, id int64, newExpiresAt time.Time) error { return r.db.WithContext(ctx).Model(&model.UserSubscription{}). Where("id = ?", id). - Updates(map[string]interface{}{ + Updates(map[string]any{ "expires_at": newExpiresAt, "updated_at": time.Now(), }).Error @@ -262,7 +262,7 @@ func (r *UserSubscriptionRepository) ExtendExpiry(ctx context.Context, id int64, func (r *UserSubscriptionRepository) UpdateNotes(ctx context.Context, id int64, notes string) error { return r.db.WithContext(ctx).Model(&model.UserSubscription{}). Where("id = ?", id). - Updates(map[string]interface{}{ + Updates(map[string]any{ "notes": notes, "updated_at": time.Now(), }).Error @@ -281,7 +281,7 @@ func (r *UserSubscriptionRepository) ListExpired(ctx context.Context) ([]model.U func (r *UserSubscriptionRepository) BatchUpdateExpiredStatus(ctx context.Context) (int64, error) { result := r.db.WithContext(ctx).Model(&model.UserSubscription{}). Where("status = ? AND expires_at <= ?", model.SubscriptionStatusActive, time.Now()). - Updates(map[string]interface{}{ + Updates(map[string]any{ "status": model.SubscriptionStatusExpired, "updated_at": time.Now(), }) diff --git a/backend/internal/service/account_service.go b/backend/internal/service/account_service.go index 6e6b31fb..b545351c 100644 --- a/backend/internal/service/account_service.go +++ b/backend/internal/service/account_service.go @@ -17,27 +17,27 @@ var ( // CreateAccountRequest 创建账号请求 type CreateAccountRequest struct { - Name string `json:"name"` - Platform string `json:"platform"` - Type string `json:"type"` - Credentials map[string]interface{} `json:"credentials"` - Extra map[string]interface{} `json:"extra"` - ProxyID *int64 `json:"proxy_id"` - Concurrency int `json:"concurrency"` - Priority int `json:"priority"` - GroupIDs []int64 `json:"group_ids"` + Name string `json:"name"` + Platform string `json:"platform"` + Type string `json:"type"` + Credentials map[string]any `json:"credentials"` + Extra map[string]any `json:"extra"` + ProxyID *int64 `json:"proxy_id"` + Concurrency int `json:"concurrency"` + Priority int `json:"priority"` + GroupIDs []int64 `json:"group_ids"` } // UpdateAccountRequest 更新账号请求 type UpdateAccountRequest struct { - Name *string `json:"name"` - Credentials *map[string]interface{} `json:"credentials"` - Extra *map[string]interface{} `json:"extra"` - ProxyID *int64 `json:"proxy_id"` - Concurrency *int `json:"concurrency"` - Priority *int `json:"priority"` - Status *string `json:"status"` - GroupIDs *[]int64 `json:"group_ids"` + Name *string `json:"name"` + Credentials *map[string]any `json:"credentials"` + Extra *map[string]any `json:"extra"` + ProxyID *int64 `json:"proxy_id"` + Concurrency *int `json:"concurrency"` + Priority *int `json:"priority"` + Status *string `json:"status"` + GroupIDs *[]int64 `json:"group_ids"` } // AccountService 账号管理服务 diff --git a/backend/internal/service/account_test_service.go b/backend/internal/service/account_test_service.go index 26ab33ff..e9bc5ec5 100644 --- a/backend/internal/service/account_test_service.go +++ b/backend/internal/service/account_test_service.go @@ -62,18 +62,18 @@ func generateSessionString() (string, error) { } // createTestPayload creates a Claude Code style test request payload -func createTestPayload(modelID string) (map[string]interface{}, error) { +func createTestPayload(modelID string) (map[string]any, error) { sessionID, err := generateSessionString() if err != nil { return nil, err } - return map[string]interface{}{ + return map[string]any{ "model": modelID, - "messages": []map[string]interface{}{ + "messages": []map[string]any{ { "role": "user", - "content": []map[string]interface{}{ + "content": []map[string]any{ { "type": "text", "text": "hi", @@ -84,7 +84,7 @@ func createTestPayload(modelID string) (map[string]interface{}, error) { }, }, }, - "system": []map[string]interface{}{ + "system": []map[string]any{ { "type": "text", "text": "You are Claude Code, Anthropic's official CLI for Claude.", @@ -262,7 +262,7 @@ func (s *AccountTestService) processStream(c *gin.Context, body io.Reader) error return nil } - var data map[string]interface{} + var data map[string]any if err := json.Unmarshal([]byte(jsonStr), &data); err != nil { continue } @@ -271,7 +271,7 @@ func (s *AccountTestService) processStream(c *gin.Context, body io.Reader) error switch eventType { case "content_block_delta": - if delta, ok := data["delta"].(map[string]interface{}); ok { + if delta, ok := data["delta"].(map[string]any); ok { if text, ok := delta["text"].(string); ok { s.sendEvent(c, TestEvent{Type: "content", Text: text}) } @@ -281,7 +281,7 @@ func (s *AccountTestService) processStream(c *gin.Context, body io.Reader) error return nil case "error": errorMsg := "Unknown error" - if errData, ok := data["error"].(map[string]interface{}); ok { + if errData, ok := data["error"].(map[string]any); ok { if msg, ok := errData["message"].(string); ok { errorMsg = msg } diff --git a/backend/internal/service/admin_service.go b/backend/internal/service/admin_service.go index 54477b37..fced40b5 100644 --- a/backend/internal/service/admin_service.go +++ b/backend/internal/service/admin_service.go @@ -24,7 +24,7 @@ type AdminService interface { DeleteUser(ctx context.Context, id int64) error UpdateUserBalance(ctx context.Context, userID int64, balance float64, operation string) (*model.User, error) GetUserAPIKeys(ctx context.Context, userID int64, page, pageSize int) ([]model.ApiKey, int64, error) - GetUserUsageStats(ctx context.Context, userID int64, period string) (interface{}, error) + GetUserUsageStats(ctx context.Context, userID int64, period string) (any, error) // Group management ListGroups(ctx context.Context, page, pageSize int, platform, status string, isExclusive *bool) ([]model.Group, int64, error) @@ -114,8 +114,8 @@ type CreateAccountInput struct { Name string Platform string Type string - Credentials map[string]interface{} - Extra map[string]interface{} + Credentials map[string]any + Extra map[string]any ProxyID *int64 Concurrency int Priority int @@ -125,8 +125,8 @@ type CreateAccountInput struct { type UpdateAccountInput struct { Name string Type string // Account type: oauth, setup-token, apikey - Credentials map[string]interface{} - Extra map[string]interface{} + Credentials map[string]any + Extra map[string]any ProxyID *int64 Concurrency *int // 使用指针区分"未提供"和"设置为0" Priority *int // 使用指针区分"未提供"和"设置为0" @@ -411,9 +411,9 @@ func (s *adminServiceImpl) GetUserAPIKeys(ctx context.Context, userID int64, pag return keys, result.Total, nil } -func (s *adminServiceImpl) GetUserUsageStats(ctx context.Context, userID int64, period string) (interface{}, error) { +func (s *adminServiceImpl) GetUserUsageStats(ctx context.Context, userID int64, period string) (any, error) { // Return mock data for now - return map[string]interface{}{ + return map[string]any{ "period": period, "total_requests": 0, "total_cost": 0.0, diff --git a/backend/internal/service/auth_service.go b/backend/internal/service/auth_service.go index def9f417..67c866f2 100644 --- a/backend/internal/service/auth_service.go +++ b/backend/internal/service/auth_service.go @@ -278,7 +278,7 @@ func (s *AuthService) Login(ctx context.Context, email, password string) (string // ValidateToken 验证JWT token并返回用户声明 func (s *AuthService) ValidateToken(tokenString string) (*JWTClaims, error) { - token, err := jwt.ParseWithClaims(tokenString, &JWTClaims{}, func(token *jwt.Token) (interface{}, error) { + token, err := jwt.ParseWithClaims(tokenString, &JWTClaims{}, func(token *jwt.Token) (any, error) { // 验证签名方法 if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok { return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"]) diff --git a/backend/internal/service/billing_service.go b/backend/internal/service/billing_service.go index e1e4f1bb..cead6327 100644 --- a/backend/internal/service/billing_service.go +++ b/backend/internal/service/billing_service.go @@ -259,11 +259,11 @@ func (s *BillingService) GetEstimatedCost(model string, estimatedInputTokens, es } // GetPricingServiceStatus 获取价格服务状态 -func (s *BillingService) GetPricingServiceStatus() map[string]interface{} { +func (s *BillingService) GetPricingServiceStatus() map[string]any { if s.pricingService != nil { return s.pricingService.GetStatus() } - return map[string]interface{}{ + return map[string]any{ "model_count": len(s.fallbackPrices), "last_updated": "using fallback", "local_hash": "N/A", diff --git a/backend/internal/service/gateway_service.go b/backend/internal/service/gateway_service.go index 826211a1..cb723463 100644 --- a/backend/internal/service/gateway_service.go +++ b/backend/internal/service/gateway_service.go @@ -122,13 +122,13 @@ func NewGatewayService( // GenerateSessionHash 从请求体计算粘性会话hash func (s *GatewayService) GenerateSessionHash(body []byte) string { - var req map[string]interface{} + var req map[string]any if err := json.Unmarshal(body, &req); err != nil { return "" } // 1. 最高优先级:从metadata.user_id提取session_xxx - if metadata, ok := req["metadata"].(map[string]interface{}); ok { + if metadata, ok := req["metadata"].(map[string]any); ok { if userID, ok := metadata["user_id"].(string); ok { re := regexp.MustCompile(`session_([a-f0-9-]{36})`) if match := re.FindStringSubmatch(userID); len(match) > 1 { @@ -152,8 +152,8 @@ func (s *GatewayService) GenerateSessionHash(body []byte) string { } // 4. 最后fallback: 使用第一条消息 - if messages, ok := req["messages"].([]interface{}); ok && len(messages) > 0 { - if firstMsg, ok := messages[0].(map[string]interface{}); ok { + if messages, ok := req["messages"].([]any); ok && len(messages) > 0 { + if firstMsg, ok := messages[0].(map[string]any); ok { msgText := s.extractTextFromContent(firstMsg["content"]) if msgText != "" { return s.hashContent(msgText) @@ -164,14 +164,14 @@ func (s *GatewayService) GenerateSessionHash(body []byte) string { return "" } -func (s *GatewayService) extractCacheableContent(req map[string]interface{}) string { +func (s *GatewayService) extractCacheableContent(req map[string]any) string { var content string // 检查system中的cacheable内容 - if system, ok := req["system"].([]interface{}); ok { + if system, ok := req["system"].([]any); ok { for _, part := range system { - if partMap, ok := part.(map[string]interface{}); ok { - if cc, ok := partMap["cache_control"].(map[string]interface{}); ok { + if partMap, ok := part.(map[string]any); ok { + if cc, ok := partMap["cache_control"].(map[string]any); ok { if cc["type"] == "ephemeral" { if text, ok := partMap["text"].(string); ok { content += text @@ -183,13 +183,13 @@ func (s *GatewayService) extractCacheableContent(req map[string]interface{}) str } // 检查messages中的cacheable内容 - if messages, ok := req["messages"].([]interface{}); ok { + if messages, ok := req["messages"].([]any); ok { for _, msg := range messages { - if msgMap, ok := msg.(map[string]interface{}); ok { - if msgContent, ok := msgMap["content"].([]interface{}); ok { + if msgMap, ok := msg.(map[string]any); ok { + if msgContent, ok := msgMap["content"].([]any); ok { for _, part := range msgContent { - if partMap, ok := part.(map[string]interface{}); ok { - if cc, ok := partMap["cache_control"].(map[string]interface{}); ok { + if partMap, ok := part.(map[string]any); ok { + if cc, ok := partMap["cache_control"].(map[string]any); ok { if cc["type"] == "ephemeral" { // 找到cacheable内容,提取第一条消息的文本 return s.extractTextFromContent(msgMap["content"]) @@ -205,14 +205,14 @@ func (s *GatewayService) extractCacheableContent(req map[string]interface{}) str return content } -func (s *GatewayService) extractTextFromSystem(system interface{}) string { +func (s *GatewayService) extractTextFromSystem(system any) string { switch v := system.(type) { case string: return v - case []interface{}: + case []any: var texts []string for _, part := range v { - if partMap, ok := part.(map[string]interface{}); ok { + if partMap, ok := part.(map[string]any); ok { if text, ok := partMap["text"].(string); ok { texts = append(texts, text) } @@ -223,14 +223,14 @@ func (s *GatewayService) extractTextFromSystem(system interface{}) string { return "" } -func (s *GatewayService) extractTextFromContent(content interface{}) string { +func (s *GatewayService) extractTextFromContent(content any) string { switch v := content.(type) { case string: return v - case []interface{}: + case []any: var texts []string for _, part := range v { - if partMap, ok := part.(map[string]interface{}); ok { + if partMap, ok := part.(map[string]any); ok { if partMap["type"] == "text" { if text, ok := partMap["text"].(string); ok { texts = append(texts, text) @@ -250,7 +250,7 @@ func (s *GatewayService) hashContent(content string) string { // replaceModelInBody 替换请求体中的model字段 func (s *GatewayService) replaceModelInBody(body []byte, newModel string) []byte { - var req map[string]interface{} + var req map[string]any if err := json.Unmarshal(body, &req); err != nil { return body } @@ -558,7 +558,7 @@ func (s *GatewayService) getBetaHeader(body []byte, clientBetaHeader string) str // 客户端没传,根据模型生成 var modelID string - var reqMap map[string]interface{} + var reqMap map[string]any if json.Unmarshal(body, &reqMap) == nil { if m, ok := reqMap["model"].(string); ok { modelID = m @@ -710,7 +710,7 @@ func (s *GatewayService) replaceModelInSSELine(line, fromModel, toModel string) return line } - var event map[string]interface{} + var event map[string]any if err := json.Unmarshal([]byte(data), &event); err != nil { return line } @@ -720,7 +720,7 @@ func (s *GatewayService) replaceModelInSSELine(line, fromModel, toModel string) return line } - msg, ok := event["message"].(map[string]interface{}) + msg, ok := event["message"].(map[string]any) if !ok { return line } @@ -802,7 +802,7 @@ func (s *GatewayService) handleNonStreamingResponse(ctx context.Context, resp *h // replaceModelInResponseBody 替换响应体中的model字段 func (s *GatewayService) replaceModelInResponseBody(body []byte, fromModel, toModel string) []byte { - var resp map[string]interface{} + var resp map[string]any if err := json.Unmarshal(body, &resp); err != nil { return body } diff --git a/backend/internal/service/group_service.go b/backend/internal/service/group_service.go index 59222740..8a49781b 100644 --- a/backend/internal/service/group_service.go +++ b/backend/internal/service/group_service.go @@ -167,7 +167,7 @@ func (s *GroupService) Delete(ctx context.Context, id int64) error { } // GetStats 获取分组统计信息 -func (s *GroupService) GetStats(ctx context.Context, id int64) (map[string]interface{}, error) { +func (s *GroupService) GetStats(ctx context.Context, id int64) (map[string]any, error) { group, err := s.groupRepo.GetByID(ctx, id) if err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { @@ -182,7 +182,7 @@ func (s *GroupService) GetStats(ctx context.Context, id int64) (map[string]inter return nil, fmt.Errorf("get account count: %w", err) } - stats := map[string]interface{}{ + stats := map[string]any{ "id": group.ID, "name": group.Name, "rate_multiplier": group.RateMultiplier, diff --git a/backend/internal/service/identity_service.go b/backend/internal/service/identity_service.go index 5493b724..25350f03 100644 --- a/backend/internal/service/identity_service.go +++ b/backend/internal/service/identity_service.go @@ -149,12 +149,12 @@ func (s *IdentityService) RewriteUserID(body []byte, accountID int64, accountUUI } // 解析JSON - var reqMap map[string]interface{} + var reqMap map[string]any if err := json.Unmarshal(body, &reqMap); err != nil { return body, nil } - metadata, ok := reqMap["metadata"].(map[string]interface{}) + metadata, ok := reqMap["metadata"].(map[string]any) if !ok { return body, nil } diff --git a/backend/internal/service/pricing_service.go b/backend/internal/service/pricing_service.go index 69b6c2ef..d91195f6 100644 --- a/backend/internal/service/pricing_service.go +++ b/backend/internal/service/pricing_service.go @@ -515,11 +515,11 @@ func (s *PricingService) matchByModelFamily(model string) *LiteLLMModelPricing { } // GetStatus 获取服务状态 -func (s *PricingService) GetStatus() map[string]interface{} { +func (s *PricingService) GetStatus() map[string]any { s.mu.RLock() defer s.mu.RUnlock() - return map[string]interface{}{ + return map[string]any{ "model_count": len(s.pricingData), "last_updated": s.lastUpdated, "local_hash": s.localHash[:min(8, len(s.localHash))], diff --git a/backend/internal/service/redeem_service.go b/backend/internal/service/redeem_service.go index 4cd97ab4..1f426882 100644 --- a/backend/internal/service/redeem_service.go +++ b/backend/internal/service/redeem_service.go @@ -359,12 +359,12 @@ func (s *RedeemService) Delete(ctx context.Context, id int64) error { } // GetStats 获取兑换码统计信息 -func (s *RedeemService) GetStats(ctx context.Context) (map[string]interface{}, error) { +func (s *RedeemService) GetStats(ctx context.Context) (map[string]any, error) { // TODO: 实现统计逻辑 // 统计未使用、已使用的兑换码数量 // 统计总面值等 - stats := map[string]interface{}{ + stats := map[string]any{ "total_codes": 0, "unused_codes": 0, "used_codes": 0, diff --git a/backend/internal/service/token_refresher.go b/backend/internal/service/token_refresher.go index b93f6858..3c152da6 100644 --- a/backend/internal/service/token_refresher.go +++ b/backend/internal/service/token_refresher.go @@ -19,7 +19,7 @@ type TokenRefresher interface { // Refresh 执行token刷新,返回更新后的credentials // 注意:返回的map应该保留原有credentials中的所有字段,只更新token相关字段 - Refresh(ctx context.Context, account *model.Account) (map[string]interface{}, error) + Refresh(ctx context.Context, account *model.Account) (map[string]any, error) } // ClaudeTokenRefresher 处理Anthropic/Claude OAuth token刷新 @@ -61,14 +61,14 @@ func (r *ClaudeTokenRefresher) NeedsRefresh(account *model.Account, refreshWindo // Refresh 执行token刷新 // 保留原有credentials中的所有字段,只更新token相关字段 -func (r *ClaudeTokenRefresher) Refresh(ctx context.Context, account *model.Account) (map[string]interface{}, error) { +func (r *ClaudeTokenRefresher) Refresh(ctx context.Context, account *model.Account) (map[string]any, error) { tokenInfo, err := r.oauthService.RefreshAccountToken(ctx, account) if err != nil { return nil, err } // 保留现有credentials中的所有字段 - newCredentials := make(map[string]interface{}) + newCredentials := make(map[string]any) for k, v := range account.Credentials { newCredentials[k] = v } diff --git a/backend/internal/service/usage_service.go b/backend/internal/service/usage_service.go index 97d13950..ead44de1 100644 --- a/backend/internal/service/usage_service.go +++ b/backend/internal/service/usage_service.go @@ -195,7 +195,7 @@ func (s *UsageService) GetStatsByModel(ctx context.Context, modelName string, st } // GetDailyStats 获取每日使用统计(最近N天) -func (s *UsageService) GetDailyStats(ctx context.Context, userID int64, days int) ([]map[string]interface{}, error) { +func (s *UsageService) GetDailyStats(ctx context.Context, userID int64, days int) ([]map[string]any, error) { endTime := time.Now() startTime := endTime.AddDate(0, 0, -days) @@ -227,13 +227,13 @@ func (s *UsageService) GetDailyStats(ctx context.Context, userID int64, days int } // 计算平均值并转换为数组 - result := make([]map[string]interface{}, 0, len(dailyStats)) + result := make([]map[string]any, 0, len(dailyStats)) for date, stats := range dailyStats { if stats.TotalRequests > 0 { stats.AverageDurationMs /= float64(stats.TotalRequests) } - result = append(result, map[string]interface{}{ + result = append(result, map[string]any{ "date": date, "total_requests": stats.TotalRequests, "total_input_tokens": stats.TotalInputTokens,