ci(backend): 添加 gofmt 配置
This commit is contained in:
@@ -571,4 +571,17 @@ linters:
|
|||||||
|
|
||||||
formatters:
|
formatters:
|
||||||
enable:
|
enable:
|
||||||
- gofmt
|
- 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:]'
|
||||||
@@ -44,29 +44,29 @@ func NewAccountHandler(adminService service.AdminService, oauthService *service.
|
|||||||
|
|
||||||
// CreateAccountRequest represents create account request
|
// CreateAccountRequest represents create account request
|
||||||
type CreateAccountRequest struct {
|
type CreateAccountRequest struct {
|
||||||
Name string `json:"name" binding:"required"`
|
Name string `json:"name" binding:"required"`
|
||||||
Platform string `json:"platform" binding:"required"`
|
Platform string `json:"platform" binding:"required"`
|
||||||
Type string `json:"type" binding:"required,oneof=oauth setup-token apikey"`
|
Type string `json:"type" binding:"required,oneof=oauth setup-token apikey"`
|
||||||
Credentials map[string]interface{} `json:"credentials" binding:"required"`
|
Credentials map[string]any `json:"credentials" binding:"required"`
|
||||||
Extra map[string]interface{} `json:"extra"`
|
Extra map[string]any `json:"extra"`
|
||||||
ProxyID *int64 `json:"proxy_id"`
|
ProxyID *int64 `json:"proxy_id"`
|
||||||
Concurrency int `json:"concurrency"`
|
Concurrency int `json:"concurrency"`
|
||||||
Priority int `json:"priority"`
|
Priority int `json:"priority"`
|
||||||
GroupIDs []int64 `json:"group_ids"`
|
GroupIDs []int64 `json:"group_ids"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// UpdateAccountRequest represents update account request
|
// UpdateAccountRequest represents update account request
|
||||||
// 使用指针类型来区分"未提供"和"设置为0"
|
// 使用指针类型来区分"未提供"和"设置为0"
|
||||||
type UpdateAccountRequest struct {
|
type UpdateAccountRequest struct {
|
||||||
Name string `json:"name"`
|
Name string `json:"name"`
|
||||||
Type string `json:"type" binding:"omitempty,oneof=oauth setup-token apikey"`
|
Type string `json:"type" binding:"omitempty,oneof=oauth setup-token apikey"`
|
||||||
Credentials map[string]interface{} `json:"credentials"`
|
Credentials map[string]any `json:"credentials"`
|
||||||
Extra map[string]interface{} `json:"extra"`
|
Extra map[string]any `json:"extra"`
|
||||||
ProxyID *int64 `json:"proxy_id"`
|
ProxyID *int64 `json:"proxy_id"`
|
||||||
Concurrency *int `json:"concurrency"`
|
Concurrency *int `json:"concurrency"`
|
||||||
Priority *int `json:"priority"`
|
Priority *int `json:"priority"`
|
||||||
Status string `json:"status" binding:"omitempty,oneof=active inactive"`
|
Status string `json:"status" binding:"omitempty,oneof=active inactive"`
|
||||||
GroupIDs *[]int64 `json:"group_ids"`
|
GroupIDs *[]int64 `json:"group_ids"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// List handles listing all accounts with pagination
|
// 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)
|
// 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 {
|
for k, v := range account.Credentials {
|
||||||
newCredentials[k] = v
|
newCredentials[k] = v
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -255,7 +255,7 @@ func (h *DashboardHandler) GetBatchUsersUsage(c *gin.Context) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if len(req.UserIDs) == 0 {
|
if len(req.UserIDs) == 0 {
|
||||||
response.Success(c, gin.H{"stats": map[string]interface{}{}})
|
response.Success(c, gin.H{"stats": map[string]any{}})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -283,7 +283,7 @@ func (h *DashboardHandler) GetBatchApiKeysUsage(c *gin.Context) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if len(req.ApiKeyIDs) == 0 {
|
if len(req.ApiKeyIDs) == 0 {
|
||||||
response.Success(c, gin.H{"stats": map[string]interface{}{}})
|
response.Success(c, gin.H{"stats": map[string]any{}})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -193,7 +193,7 @@ func (h *UsageHandler) Stats(c *gin.Context) {
|
|||||||
func (h *UsageHandler) SearchUsers(c *gin.Context) {
|
func (h *UsageHandler) SearchUsers(c *gin.Context) {
|
||||||
keyword := c.Query("q")
|
keyword := c.Query("q")
|
||||||
if keyword == "" {
|
if keyword == "" {
|
||||||
response.Success(c, []interface{}{})
|
response.Success(c, []any{})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -358,7 +358,7 @@ func (h *UsageHandler) DashboardApiKeysUsage(c *gin.Context) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if len(req.ApiKeyIDs) == 0 {
|
if len(req.ApiKeyIDs) == 0 {
|
||||||
response.Success(c, gin.H{"stats": map[string]interface{}{}})
|
response.Success(c, gin.H{"stats": map[string]any{}})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -383,7 +383,7 @@ func (h *UsageHandler) DashboardApiKeysUsage(c *gin.Context) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if len(validApiKeyIDs) == 0 {
|
if len(validApiKeyIDs) == 0 {
|
||||||
response.Success(c, gin.H{"stats": map[string]interface{}{}})
|
response.Success(c, gin.H{"stats": map[string]any{}})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
// JSONB 用于存储JSONB数据
|
// JSONB 用于存储JSONB数据
|
||||||
type JSONB map[string]interface{}
|
type JSONB map[string]any
|
||||||
|
|
||||||
func (j JSONB) Value() (driver.Value, error) {
|
func (j JSONB) Value() (driver.Value, error) {
|
||||||
if j == nil {
|
if j == nil {
|
||||||
@@ -19,7 +19,7 @@ func (j JSONB) Value() (driver.Value, error) {
|
|||||||
return json.Marshal(j)
|
return json.Marshal(j)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (j *JSONB) Scan(value interface{}) error {
|
func (j *JSONB) Scan(value any) error {
|
||||||
if value == nil {
|
if value == nil {
|
||||||
*j = nil
|
*j = nil
|
||||||
return nil
|
return nil
|
||||||
@@ -145,7 +145,7 @@ func (a *Account) GetModelMapping() map[string]string {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
// 处理map[string]interface{}类型
|
// 处理map[string]interface{}类型
|
||||||
if m, ok := raw.(map[string]interface{}); ok {
|
if m, ok := raw.(map[string]any); ok {
|
||||||
result := make(map[string]string)
|
result := make(map[string]string)
|
||||||
for k, v := range m {
|
for k, v := range m {
|
||||||
if s, ok := v.(string); ok {
|
if s, ok := v.(string); ok {
|
||||||
@@ -231,7 +231,7 @@ func (a *Account) GetCustomErrorCodes() []int {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
// 处理 []interface{} 类型(JSON反序列化后的格式)
|
// 处理 []interface{} 类型(JSON反序列化后的格式)
|
||||||
if arr, ok := raw.([]interface{}); ok {
|
if arr, ok := raw.([]any); ok {
|
||||||
result := make([]int, 0, len(arr))
|
result := make([]int, 0, len(arr))
|
||||||
for _, v := range arr {
|
for _, v := range arr {
|
||||||
// JSON 数字默认解析为 float64
|
// JSON 数字默认解析为 float64
|
||||||
|
|||||||
@@ -9,22 +9,22 @@ import (
|
|||||||
|
|
||||||
// Response 标准API响应格式
|
// Response 标准API响应格式
|
||||||
type Response struct {
|
type Response struct {
|
||||||
Code int `json:"code"`
|
Code int `json:"code"`
|
||||||
Message string `json:"message"`
|
Message string `json:"message"`
|
||||||
Data interface{} `json:"data,omitempty"`
|
Data any `json:"data,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// PaginatedData 分页数据格式(匹配前端期望)
|
// PaginatedData 分页数据格式(匹配前端期望)
|
||||||
type PaginatedData struct {
|
type PaginatedData struct {
|
||||||
Items interface{} `json:"items"`
|
Items any `json:"items"`
|
||||||
Total int64 `json:"total"`
|
Total int64 `json:"total"`
|
||||||
Page int `json:"page"`
|
Page int `json:"page"`
|
||||||
PageSize int `json:"page_size"`
|
PageSize int `json:"page_size"`
|
||||||
Pages int `json:"pages"`
|
Pages int `json:"pages"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// Success 返回成功响应
|
// Success 返回成功响应
|
||||||
func Success(c *gin.Context, data interface{}) {
|
func Success(c *gin.Context, data any) {
|
||||||
c.JSON(http.StatusOK, Response{
|
c.JSON(http.StatusOK, Response{
|
||||||
Code: 0,
|
Code: 0,
|
||||||
Message: "success",
|
Message: "success",
|
||||||
@@ -33,7 +33,7 @@ func Success(c *gin.Context, data interface{}) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Created 返回创建成功响应
|
// Created 返回创建成功响应
|
||||||
func Created(c *gin.Context, data interface{}) {
|
func Created(c *gin.Context, data any) {
|
||||||
c.JSON(http.StatusCreated, Response{
|
c.JSON(http.StatusCreated, Response{
|
||||||
Code: 0,
|
Code: 0,
|
||||||
Message: "success",
|
Message: "success",
|
||||||
@@ -75,7 +75,7 @@ func InternalError(c *gin.Context, message string) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Paginated 返回分页数据
|
// 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)))
|
pages := int(math.Ceil(float64(total) / float64(pageSize)))
|
||||||
if pages < 1 {
|
if pages < 1 {
|
||||||
pages = 1
|
pages = 1
|
||||||
@@ -99,7 +99,7 @@ type PaginationResult struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// PaginatedWithResult 使用PaginationResult返回分页数据
|
// PaginatedWithResult 使用PaginationResult返回分页数据
|
||||||
func PaginatedWithResult(c *gin.Context, items interface{}, pagination *PaginationResult) {
|
func PaginatedWithResult(c *gin.Context, items any, pagination *PaginationResult) {
|
||||||
if pagination == nil {
|
if pagination == nil {
|
||||||
Success(c, PaginatedData{
|
Success(c, PaginatedData{
|
||||||
Items: items,
|
Items: items,
|
||||||
|
|||||||
@@ -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 {
|
func (r *AccountRepository) SetError(ctx context.Context, id int64, errorMsg string) error {
|
||||||
return r.db.WithContext(ctx).Model(&model.Account{}).Where("id = ?", id).
|
return r.db.WithContext(ctx).Model(&model.Account{}).Where("id = ?", id).
|
||||||
Updates(map[string]interface{}{
|
Updates(map[string]any{
|
||||||
"status": model.StatusError,
|
"status": model.StatusError,
|
||||||
"error_message": errorMsg,
|
"error_message": errorMsg,
|
||||||
}).Error
|
}).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 {
|
func (r *AccountRepository) SetRateLimited(ctx context.Context, id int64, resetAt time.Time) error {
|
||||||
now := time.Now()
|
now := time.Now()
|
||||||
return r.db.WithContext(ctx).Model(&model.Account{}).Where("id = ?", id).
|
return r.db.WithContext(ctx).Model(&model.Account{}).Where("id = ?", id).
|
||||||
Updates(map[string]interface{}{
|
Updates(map[string]any{
|
||||||
"rate_limited_at": now,
|
"rate_limited_at": now,
|
||||||
"rate_limit_reset_at": resetAt,
|
"rate_limit_reset_at": resetAt,
|
||||||
}).Error
|
}).Error
|
||||||
@@ -241,7 +241,7 @@ func (r *AccountRepository) SetOverloaded(ctx context.Context, id int64, until t
|
|||||||
// ClearRateLimit 清除账号的限流状态
|
// ClearRateLimit 清除账号的限流状态
|
||||||
func (r *AccountRepository) ClearRateLimit(ctx context.Context, id int64) error {
|
func (r *AccountRepository) ClearRateLimit(ctx context.Context, id int64) error {
|
||||||
return r.db.WithContext(ctx).Model(&model.Account{}).Where("id = ?", id).
|
return r.db.WithContext(ctx).Model(&model.Account{}).Where("id = ?", id).
|
||||||
Updates(map[string]interface{}{
|
Updates(map[string]any{
|
||||||
"rate_limited_at": nil,
|
"rate_limited_at": nil,
|
||||||
"rate_limit_reset_at": nil,
|
"rate_limit_reset_at": nil,
|
||||||
"overload_until": nil,
|
"overload_until": nil,
|
||||||
@@ -250,7 +250,7 @@ func (r *AccountRepository) ClearRateLimit(ctx context.Context, id int64) error
|
|||||||
|
|
||||||
// UpdateSessionWindow 更新账号的5小时时间窗口信息
|
// UpdateSessionWindow 更新账号的5小时时间窗口信息
|
||||||
func (r *AccountRepository) UpdateSessionWindow(ctx context.Context, id int64, start, end *time.Time, status string) error {
|
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,
|
"session_window_status": status,
|
||||||
}
|
}
|
||||||
if start != nil {
|
if start != nil {
|
||||||
|
|||||||
@@ -143,7 +143,7 @@ func (c *billingCache) SetSubscriptionCache(ctx context.Context, userID, groupID
|
|||||||
|
|
||||||
key := fmt.Sprintf("%s%d:%d", billingSubKeyPrefix, userID, groupID)
|
key := fmt.Sprintf("%s%d:%d", billingSubKeyPrefix, userID, groupID)
|
||||||
|
|
||||||
fields := map[string]interface{}{
|
fields := map[string]any{
|
||||||
subFieldStatus: data.Status,
|
subFieldStatus: data.Status,
|
||||||
subFieldExpiresAt: data.ExpiresAt.Unix(),
|
subFieldExpiresAt: data.ExpiresAt.Unix(),
|
||||||
subFieldDailyUsage: data.DailyUsage,
|
subFieldDailyUsage: data.DailyUsage,
|
||||||
|
|||||||
@@ -64,7 +64,7 @@ func (s *claudeOAuthService) GetAuthorizationCode(ctx context.Context, sessionKe
|
|||||||
|
|
||||||
authURL := fmt.Sprintf("https://claude.ai/v1/oauth/%s/authorize", orgUUID)
|
authURL := fmt.Sprintf("https://claude.ai/v1/oauth/%s/authorize", orgUUID)
|
||||||
|
|
||||||
reqBody := map[string]interface{}{
|
reqBody := map[string]any{
|
||||||
"response_type": "code",
|
"response_type": "code",
|
||||||
"client_id": oauth.ClientID,
|
"client_id": oauth.ClientID,
|
||||||
"organization_uuid": orgUUID,
|
"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,
|
"code": authCode,
|
||||||
"grant_type": "authorization_code",
|
"grant_type": "authorization_code",
|
||||||
"client_id": oauth.ClientID,
|
"client_id": oauth.ClientID,
|
||||||
|
|||||||
@@ -99,7 +99,7 @@ func (r *RedeemCodeRepository) Use(ctx context.Context, id, userID int64) error
|
|||||||
now := time.Now()
|
now := time.Now()
|
||||||
result := r.db.WithContext(ctx).Model(&model.RedeemCode{}).
|
result := r.db.WithContext(ctx).Model(&model.RedeemCode{}).
|
||||||
Where("id = ? AND status = ?", id, model.StatusUnused).
|
Where("id = ? AND status = ?", id, model.StatusUnused).
|
||||||
Updates(map[string]interface{}{
|
Updates(map[string]any{
|
||||||
"status": model.StatusUsed,
|
"status": model.StatusUsed,
|
||||||
"used_by": userID,
|
"used_by": userID,
|
||||||
"used_at": now,
|
"used_at": now,
|
||||||
|
|||||||
@@ -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 {
|
func (r *UserSubscriptionRepository) IncrementUsage(ctx context.Context, id int64, costUSD float64) error {
|
||||||
return r.db.WithContext(ctx).Model(&model.UserSubscription{}).
|
return r.db.WithContext(ctx).Model(&model.UserSubscription{}).
|
||||||
Where("id = ?", id).
|
Where("id = ?", id).
|
||||||
Updates(map[string]interface{}{
|
Updates(map[string]any{
|
||||||
"daily_usage_usd": gorm.Expr("daily_usage_usd + ?", costUSD),
|
"daily_usage_usd": gorm.Expr("daily_usage_usd + ?", costUSD),
|
||||||
"weekly_usage_usd": gorm.Expr("weekly_usage_usd + ?", costUSD),
|
"weekly_usage_usd": gorm.Expr("weekly_usage_usd + ?", costUSD),
|
||||||
"monthly_usage_usd": gorm.Expr("monthly_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 {
|
func (r *UserSubscriptionRepository) ResetDailyUsage(ctx context.Context, id int64, newWindowStart time.Time) error {
|
||||||
return r.db.WithContext(ctx).Model(&model.UserSubscription{}).
|
return r.db.WithContext(ctx).Model(&model.UserSubscription{}).
|
||||||
Where("id = ?", id).
|
Where("id = ?", id).
|
||||||
Updates(map[string]interface{}{
|
Updates(map[string]any{
|
||||||
"daily_usage_usd": 0,
|
"daily_usage_usd": 0,
|
||||||
"daily_window_start": newWindowStart,
|
"daily_window_start": newWindowStart,
|
||||||
"updated_at": time.Now(),
|
"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 {
|
func (r *UserSubscriptionRepository) ResetWeeklyUsage(ctx context.Context, id int64, newWindowStart time.Time) error {
|
||||||
return r.db.WithContext(ctx).Model(&model.UserSubscription{}).
|
return r.db.WithContext(ctx).Model(&model.UserSubscription{}).
|
||||||
Where("id = ?", id).
|
Where("id = ?", id).
|
||||||
Updates(map[string]interface{}{
|
Updates(map[string]any{
|
||||||
"weekly_usage_usd": 0,
|
"weekly_usage_usd": 0,
|
||||||
"weekly_window_start": newWindowStart,
|
"weekly_window_start": newWindowStart,
|
||||||
"updated_at": time.Now(),
|
"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 {
|
func (r *UserSubscriptionRepository) ResetMonthlyUsage(ctx context.Context, id int64, newWindowStart time.Time) error {
|
||||||
return r.db.WithContext(ctx).Model(&model.UserSubscription{}).
|
return r.db.WithContext(ctx).Model(&model.UserSubscription{}).
|
||||||
Where("id = ?", id).
|
Where("id = ?", id).
|
||||||
Updates(map[string]interface{}{
|
Updates(map[string]any{
|
||||||
"monthly_usage_usd": 0,
|
"monthly_usage_usd": 0,
|
||||||
"monthly_window_start": newWindowStart,
|
"monthly_window_start": newWindowStart,
|
||||||
"updated_at": time.Now(),
|
"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 {
|
func (r *UserSubscriptionRepository) ActivateWindows(ctx context.Context, id int64, activateTime time.Time) error {
|
||||||
return r.db.WithContext(ctx).Model(&model.UserSubscription{}).
|
return r.db.WithContext(ctx).Model(&model.UserSubscription{}).
|
||||||
Where("id = ?", id).
|
Where("id = ?", id).
|
||||||
Updates(map[string]interface{}{
|
Updates(map[string]any{
|
||||||
"daily_window_start": activateTime,
|
"daily_window_start": activateTime,
|
||||||
"weekly_window_start": activateTime,
|
"weekly_window_start": activateTime,
|
||||||
"monthly_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 {
|
func (r *UserSubscriptionRepository) UpdateStatus(ctx context.Context, id int64, status string) error {
|
||||||
return r.db.WithContext(ctx).Model(&model.UserSubscription{}).
|
return r.db.WithContext(ctx).Model(&model.UserSubscription{}).
|
||||||
Where("id = ?", id).
|
Where("id = ?", id).
|
||||||
Updates(map[string]interface{}{
|
Updates(map[string]any{
|
||||||
"status": status,
|
"status": status,
|
||||||
"updated_at": time.Now(),
|
"updated_at": time.Now(),
|
||||||
}).Error
|
}).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 {
|
func (r *UserSubscriptionRepository) ExtendExpiry(ctx context.Context, id int64, newExpiresAt time.Time) error {
|
||||||
return r.db.WithContext(ctx).Model(&model.UserSubscription{}).
|
return r.db.WithContext(ctx).Model(&model.UserSubscription{}).
|
||||||
Where("id = ?", id).
|
Where("id = ?", id).
|
||||||
Updates(map[string]interface{}{
|
Updates(map[string]any{
|
||||||
"expires_at": newExpiresAt,
|
"expires_at": newExpiresAt,
|
||||||
"updated_at": time.Now(),
|
"updated_at": time.Now(),
|
||||||
}).Error
|
}).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 {
|
func (r *UserSubscriptionRepository) UpdateNotes(ctx context.Context, id int64, notes string) error {
|
||||||
return r.db.WithContext(ctx).Model(&model.UserSubscription{}).
|
return r.db.WithContext(ctx).Model(&model.UserSubscription{}).
|
||||||
Where("id = ?", id).
|
Where("id = ?", id).
|
||||||
Updates(map[string]interface{}{
|
Updates(map[string]any{
|
||||||
"notes": notes,
|
"notes": notes,
|
||||||
"updated_at": time.Now(),
|
"updated_at": time.Now(),
|
||||||
}).Error
|
}).Error
|
||||||
@@ -281,7 +281,7 @@ func (r *UserSubscriptionRepository) ListExpired(ctx context.Context) ([]model.U
|
|||||||
func (r *UserSubscriptionRepository) BatchUpdateExpiredStatus(ctx context.Context) (int64, error) {
|
func (r *UserSubscriptionRepository) BatchUpdateExpiredStatus(ctx context.Context) (int64, error) {
|
||||||
result := r.db.WithContext(ctx).Model(&model.UserSubscription{}).
|
result := r.db.WithContext(ctx).Model(&model.UserSubscription{}).
|
||||||
Where("status = ? AND expires_at <= ?", model.SubscriptionStatusActive, time.Now()).
|
Where("status = ? AND expires_at <= ?", model.SubscriptionStatusActive, time.Now()).
|
||||||
Updates(map[string]interface{}{
|
Updates(map[string]any{
|
||||||
"status": model.SubscriptionStatusExpired,
|
"status": model.SubscriptionStatusExpired,
|
||||||
"updated_at": time.Now(),
|
"updated_at": time.Now(),
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -17,27 +17,27 @@ var (
|
|||||||
|
|
||||||
// CreateAccountRequest 创建账号请求
|
// CreateAccountRequest 创建账号请求
|
||||||
type CreateAccountRequest struct {
|
type CreateAccountRequest struct {
|
||||||
Name string `json:"name"`
|
Name string `json:"name"`
|
||||||
Platform string `json:"platform"`
|
Platform string `json:"platform"`
|
||||||
Type string `json:"type"`
|
Type string `json:"type"`
|
||||||
Credentials map[string]interface{} `json:"credentials"`
|
Credentials map[string]any `json:"credentials"`
|
||||||
Extra map[string]interface{} `json:"extra"`
|
Extra map[string]any `json:"extra"`
|
||||||
ProxyID *int64 `json:"proxy_id"`
|
ProxyID *int64 `json:"proxy_id"`
|
||||||
Concurrency int `json:"concurrency"`
|
Concurrency int `json:"concurrency"`
|
||||||
Priority int `json:"priority"`
|
Priority int `json:"priority"`
|
||||||
GroupIDs []int64 `json:"group_ids"`
|
GroupIDs []int64 `json:"group_ids"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// UpdateAccountRequest 更新账号请求
|
// UpdateAccountRequest 更新账号请求
|
||||||
type UpdateAccountRequest struct {
|
type UpdateAccountRequest struct {
|
||||||
Name *string `json:"name"`
|
Name *string `json:"name"`
|
||||||
Credentials *map[string]interface{} `json:"credentials"`
|
Credentials *map[string]any `json:"credentials"`
|
||||||
Extra *map[string]interface{} `json:"extra"`
|
Extra *map[string]any `json:"extra"`
|
||||||
ProxyID *int64 `json:"proxy_id"`
|
ProxyID *int64 `json:"proxy_id"`
|
||||||
Concurrency *int `json:"concurrency"`
|
Concurrency *int `json:"concurrency"`
|
||||||
Priority *int `json:"priority"`
|
Priority *int `json:"priority"`
|
||||||
Status *string `json:"status"`
|
Status *string `json:"status"`
|
||||||
GroupIDs *[]int64 `json:"group_ids"`
|
GroupIDs *[]int64 `json:"group_ids"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// AccountService 账号管理服务
|
// AccountService 账号管理服务
|
||||||
|
|||||||
@@ -62,18 +62,18 @@ func generateSessionString() (string, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// createTestPayload creates a Claude Code style test request payload
|
// 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()
|
sessionID, err := generateSessionString()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
return map[string]interface{}{
|
return map[string]any{
|
||||||
"model": modelID,
|
"model": modelID,
|
||||||
"messages": []map[string]interface{}{
|
"messages": []map[string]any{
|
||||||
{
|
{
|
||||||
"role": "user",
|
"role": "user",
|
||||||
"content": []map[string]interface{}{
|
"content": []map[string]any{
|
||||||
{
|
{
|
||||||
"type": "text",
|
"type": "text",
|
||||||
"text": "hi",
|
"text": "hi",
|
||||||
@@ -84,7 +84,7 @@ func createTestPayload(modelID string) (map[string]interface{}, error) {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
"system": []map[string]interface{}{
|
"system": []map[string]any{
|
||||||
{
|
{
|
||||||
"type": "text",
|
"type": "text",
|
||||||
"text": "You are Claude Code, Anthropic's official CLI for Claude.",
|
"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
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
var data map[string]interface{}
|
var data map[string]any
|
||||||
if err := json.Unmarshal([]byte(jsonStr), &data); err != nil {
|
if err := json.Unmarshal([]byte(jsonStr), &data); err != nil {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
@@ -271,7 +271,7 @@ func (s *AccountTestService) processStream(c *gin.Context, body io.Reader) error
|
|||||||
|
|
||||||
switch eventType {
|
switch eventType {
|
||||||
case "content_block_delta":
|
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 {
|
if text, ok := delta["text"].(string); ok {
|
||||||
s.sendEvent(c, TestEvent{Type: "content", Text: text})
|
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
|
return nil
|
||||||
case "error":
|
case "error":
|
||||||
errorMsg := "Unknown 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 {
|
if msg, ok := errData["message"].(string); ok {
|
||||||
errorMsg = msg
|
errorMsg = msg
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -24,7 +24,7 @@ type AdminService interface {
|
|||||||
DeleteUser(ctx context.Context, id int64) error
|
DeleteUser(ctx context.Context, id int64) error
|
||||||
UpdateUserBalance(ctx context.Context, userID int64, balance float64, operation string) (*model.User, 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)
|
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
|
// Group management
|
||||||
ListGroups(ctx context.Context, page, pageSize int, platform, status string, isExclusive *bool) ([]model.Group, int64, error)
|
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
|
Name string
|
||||||
Platform string
|
Platform string
|
||||||
Type string
|
Type string
|
||||||
Credentials map[string]interface{}
|
Credentials map[string]any
|
||||||
Extra map[string]interface{}
|
Extra map[string]any
|
||||||
ProxyID *int64
|
ProxyID *int64
|
||||||
Concurrency int
|
Concurrency int
|
||||||
Priority int
|
Priority int
|
||||||
@@ -125,8 +125,8 @@ type CreateAccountInput struct {
|
|||||||
type UpdateAccountInput struct {
|
type UpdateAccountInput struct {
|
||||||
Name string
|
Name string
|
||||||
Type string // Account type: oauth, setup-token, apikey
|
Type string // Account type: oauth, setup-token, apikey
|
||||||
Credentials map[string]interface{}
|
Credentials map[string]any
|
||||||
Extra map[string]interface{}
|
Extra map[string]any
|
||||||
ProxyID *int64
|
ProxyID *int64
|
||||||
Concurrency *int // 使用指针区分"未提供"和"设置为0"
|
Concurrency *int // 使用指针区分"未提供"和"设置为0"
|
||||||
Priority *int // 使用指针区分"未提供"和"设置为0"
|
Priority *int // 使用指针区分"未提供"和"设置为0"
|
||||||
@@ -411,9 +411,9 @@ func (s *adminServiceImpl) GetUserAPIKeys(ctx context.Context, userID int64, pag
|
|||||||
return keys, result.Total, nil
|
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 mock data for now
|
||||||
return map[string]interface{}{
|
return map[string]any{
|
||||||
"period": period,
|
"period": period,
|
||||||
"total_requests": 0,
|
"total_requests": 0,
|
||||||
"total_cost": 0.0,
|
"total_cost": 0.0,
|
||||||
|
|||||||
@@ -278,7 +278,7 @@ func (s *AuthService) Login(ctx context.Context, email, password string) (string
|
|||||||
|
|
||||||
// ValidateToken 验证JWT token并返回用户声明
|
// ValidateToken 验证JWT token并返回用户声明
|
||||||
func (s *AuthService) ValidateToken(tokenString string) (*JWTClaims, error) {
|
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 {
|
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
|
||||||
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
|
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
|
||||||
|
|||||||
@@ -259,11 +259,11 @@ func (s *BillingService) GetEstimatedCost(model string, estimatedInputTokens, es
|
|||||||
}
|
}
|
||||||
|
|
||||||
// GetPricingServiceStatus 获取价格服务状态
|
// GetPricingServiceStatus 获取价格服务状态
|
||||||
func (s *BillingService) GetPricingServiceStatus() map[string]interface{} {
|
func (s *BillingService) GetPricingServiceStatus() map[string]any {
|
||||||
if s.pricingService != nil {
|
if s.pricingService != nil {
|
||||||
return s.pricingService.GetStatus()
|
return s.pricingService.GetStatus()
|
||||||
}
|
}
|
||||||
return map[string]interface{}{
|
return map[string]any{
|
||||||
"model_count": len(s.fallbackPrices),
|
"model_count": len(s.fallbackPrices),
|
||||||
"last_updated": "using fallback",
|
"last_updated": "using fallback",
|
||||||
"local_hash": "N/A",
|
"local_hash": "N/A",
|
||||||
|
|||||||
@@ -122,13 +122,13 @@ func NewGatewayService(
|
|||||||
|
|
||||||
// GenerateSessionHash 从请求体计算粘性会话hash
|
// GenerateSessionHash 从请求体计算粘性会话hash
|
||||||
func (s *GatewayService) GenerateSessionHash(body []byte) string {
|
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 {
|
if err := json.Unmarshal(body, &req); err != nil {
|
||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
|
|
||||||
// 1. 最高优先级:从metadata.user_id提取session_xxx
|
// 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 {
|
if userID, ok := metadata["user_id"].(string); ok {
|
||||||
re := regexp.MustCompile(`session_([a-f0-9-]{36})`)
|
re := regexp.MustCompile(`session_([a-f0-9-]{36})`)
|
||||||
if match := re.FindStringSubmatch(userID); len(match) > 1 {
|
if match := re.FindStringSubmatch(userID); len(match) > 1 {
|
||||||
@@ -152,8 +152,8 @@ func (s *GatewayService) GenerateSessionHash(body []byte) string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 4. 最后fallback: 使用第一条消息
|
// 4. 最后fallback: 使用第一条消息
|
||||||
if messages, ok := req["messages"].([]interface{}); ok && len(messages) > 0 {
|
if messages, ok := req["messages"].([]any); ok && len(messages) > 0 {
|
||||||
if firstMsg, ok := messages[0].(map[string]interface{}); ok {
|
if firstMsg, ok := messages[0].(map[string]any); ok {
|
||||||
msgText := s.extractTextFromContent(firstMsg["content"])
|
msgText := s.extractTextFromContent(firstMsg["content"])
|
||||||
if msgText != "" {
|
if msgText != "" {
|
||||||
return s.hashContent(msgText)
|
return s.hashContent(msgText)
|
||||||
@@ -164,14 +164,14 @@ func (s *GatewayService) GenerateSessionHash(body []byte) string {
|
|||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *GatewayService) extractCacheableContent(req map[string]interface{}) string {
|
func (s *GatewayService) extractCacheableContent(req map[string]any) string {
|
||||||
var content string
|
var content string
|
||||||
|
|
||||||
// 检查system中的cacheable内容
|
// 检查system中的cacheable内容
|
||||||
if system, ok := req["system"].([]interface{}); ok {
|
if system, ok := req["system"].([]any); ok {
|
||||||
for _, part := range system {
|
for _, part := range system {
|
||||||
if partMap, ok := part.(map[string]interface{}); ok {
|
if partMap, ok := part.(map[string]any); ok {
|
||||||
if cc, ok := partMap["cache_control"].(map[string]interface{}); ok {
|
if cc, ok := partMap["cache_control"].(map[string]any); ok {
|
||||||
if cc["type"] == "ephemeral" {
|
if cc["type"] == "ephemeral" {
|
||||||
if text, ok := partMap["text"].(string); ok {
|
if text, ok := partMap["text"].(string); ok {
|
||||||
content += text
|
content += text
|
||||||
@@ -183,13 +183,13 @@ func (s *GatewayService) extractCacheableContent(req map[string]interface{}) str
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 检查messages中的cacheable内容
|
// 检查messages中的cacheable内容
|
||||||
if messages, ok := req["messages"].([]interface{}); ok {
|
if messages, ok := req["messages"].([]any); ok {
|
||||||
for _, msg := range messages {
|
for _, msg := range messages {
|
||||||
if msgMap, ok := msg.(map[string]interface{}); ok {
|
if msgMap, ok := msg.(map[string]any); ok {
|
||||||
if msgContent, ok := msgMap["content"].([]interface{}); ok {
|
if msgContent, ok := msgMap["content"].([]any); ok {
|
||||||
for _, part := range msgContent {
|
for _, part := range msgContent {
|
||||||
if partMap, ok := part.(map[string]interface{}); ok {
|
if partMap, ok := part.(map[string]any); ok {
|
||||||
if cc, ok := partMap["cache_control"].(map[string]interface{}); ok {
|
if cc, ok := partMap["cache_control"].(map[string]any); ok {
|
||||||
if cc["type"] == "ephemeral" {
|
if cc["type"] == "ephemeral" {
|
||||||
// 找到cacheable内容,提取第一条消息的文本
|
// 找到cacheable内容,提取第一条消息的文本
|
||||||
return s.extractTextFromContent(msgMap["content"])
|
return s.extractTextFromContent(msgMap["content"])
|
||||||
@@ -205,14 +205,14 @@ func (s *GatewayService) extractCacheableContent(req map[string]interface{}) str
|
|||||||
return content
|
return content
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *GatewayService) extractTextFromSystem(system interface{}) string {
|
func (s *GatewayService) extractTextFromSystem(system any) string {
|
||||||
switch v := system.(type) {
|
switch v := system.(type) {
|
||||||
case string:
|
case string:
|
||||||
return v
|
return v
|
||||||
case []interface{}:
|
case []any:
|
||||||
var texts []string
|
var texts []string
|
||||||
for _, part := range v {
|
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 {
|
if text, ok := partMap["text"].(string); ok {
|
||||||
texts = append(texts, text)
|
texts = append(texts, text)
|
||||||
}
|
}
|
||||||
@@ -223,14 +223,14 @@ func (s *GatewayService) extractTextFromSystem(system interface{}) string {
|
|||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *GatewayService) extractTextFromContent(content interface{}) string {
|
func (s *GatewayService) extractTextFromContent(content any) string {
|
||||||
switch v := content.(type) {
|
switch v := content.(type) {
|
||||||
case string:
|
case string:
|
||||||
return v
|
return v
|
||||||
case []interface{}:
|
case []any:
|
||||||
var texts []string
|
var texts []string
|
||||||
for _, part := range v {
|
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 partMap["type"] == "text" {
|
||||||
if text, ok := partMap["text"].(string); ok {
|
if text, ok := partMap["text"].(string); ok {
|
||||||
texts = append(texts, text)
|
texts = append(texts, text)
|
||||||
@@ -250,7 +250,7 @@ func (s *GatewayService) hashContent(content string) string {
|
|||||||
|
|
||||||
// replaceModelInBody 替换请求体中的model字段
|
// replaceModelInBody 替换请求体中的model字段
|
||||||
func (s *GatewayService) replaceModelInBody(body []byte, newModel string) []byte {
|
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 {
|
if err := json.Unmarshal(body, &req); err != nil {
|
||||||
return body
|
return body
|
||||||
}
|
}
|
||||||
@@ -558,7 +558,7 @@ func (s *GatewayService) getBetaHeader(body []byte, clientBetaHeader string) str
|
|||||||
|
|
||||||
// 客户端没传,根据模型生成
|
// 客户端没传,根据模型生成
|
||||||
var modelID string
|
var modelID string
|
||||||
var reqMap map[string]interface{}
|
var reqMap map[string]any
|
||||||
if json.Unmarshal(body, &reqMap) == nil {
|
if json.Unmarshal(body, &reqMap) == nil {
|
||||||
if m, ok := reqMap["model"].(string); ok {
|
if m, ok := reqMap["model"].(string); ok {
|
||||||
modelID = m
|
modelID = m
|
||||||
@@ -710,7 +710,7 @@ func (s *GatewayService) replaceModelInSSELine(line, fromModel, toModel string)
|
|||||||
return line
|
return line
|
||||||
}
|
}
|
||||||
|
|
||||||
var event map[string]interface{}
|
var event map[string]any
|
||||||
if err := json.Unmarshal([]byte(data), &event); err != nil {
|
if err := json.Unmarshal([]byte(data), &event); err != nil {
|
||||||
return line
|
return line
|
||||||
}
|
}
|
||||||
@@ -720,7 +720,7 @@ func (s *GatewayService) replaceModelInSSELine(line, fromModel, toModel string)
|
|||||||
return line
|
return line
|
||||||
}
|
}
|
||||||
|
|
||||||
msg, ok := event["message"].(map[string]interface{})
|
msg, ok := event["message"].(map[string]any)
|
||||||
if !ok {
|
if !ok {
|
||||||
return line
|
return line
|
||||||
}
|
}
|
||||||
@@ -802,7 +802,7 @@ func (s *GatewayService) handleNonStreamingResponse(ctx context.Context, resp *h
|
|||||||
|
|
||||||
// replaceModelInResponseBody 替换响应体中的model字段
|
// replaceModelInResponseBody 替换响应体中的model字段
|
||||||
func (s *GatewayService) replaceModelInResponseBody(body []byte, fromModel, toModel string) []byte {
|
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 {
|
if err := json.Unmarshal(body, &resp); err != nil {
|
||||||
return body
|
return body
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -167,7 +167,7 @@ func (s *GroupService) Delete(ctx context.Context, id int64) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// GetStats 获取分组统计信息
|
// 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)
|
group, err := s.groupRepo.GetByID(ctx, id)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
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)
|
return nil, fmt.Errorf("get account count: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
stats := map[string]interface{}{
|
stats := map[string]any{
|
||||||
"id": group.ID,
|
"id": group.ID,
|
||||||
"name": group.Name,
|
"name": group.Name,
|
||||||
"rate_multiplier": group.RateMultiplier,
|
"rate_multiplier": group.RateMultiplier,
|
||||||
|
|||||||
@@ -149,12 +149,12 @@ func (s *IdentityService) RewriteUserID(body []byte, accountID int64, accountUUI
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 解析JSON
|
// 解析JSON
|
||||||
var reqMap map[string]interface{}
|
var reqMap map[string]any
|
||||||
if err := json.Unmarshal(body, &reqMap); err != nil {
|
if err := json.Unmarshal(body, &reqMap); err != nil {
|
||||||
return body, nil
|
return body, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
metadata, ok := reqMap["metadata"].(map[string]interface{})
|
metadata, ok := reqMap["metadata"].(map[string]any)
|
||||||
if !ok {
|
if !ok {
|
||||||
return body, nil
|
return body, nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -515,11 +515,11 @@ func (s *PricingService) matchByModelFamily(model string) *LiteLLMModelPricing {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// GetStatus 获取服务状态
|
// GetStatus 获取服务状态
|
||||||
func (s *PricingService) GetStatus() map[string]interface{} {
|
func (s *PricingService) GetStatus() map[string]any {
|
||||||
s.mu.RLock()
|
s.mu.RLock()
|
||||||
defer s.mu.RUnlock()
|
defer s.mu.RUnlock()
|
||||||
|
|
||||||
return map[string]interface{}{
|
return map[string]any{
|
||||||
"model_count": len(s.pricingData),
|
"model_count": len(s.pricingData),
|
||||||
"last_updated": s.lastUpdated,
|
"last_updated": s.lastUpdated,
|
||||||
"local_hash": s.localHash[:min(8, len(s.localHash))],
|
"local_hash": s.localHash[:min(8, len(s.localHash))],
|
||||||
|
|||||||
@@ -359,12 +359,12 @@ func (s *RedeemService) Delete(ctx context.Context, id int64) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// GetStats 获取兑换码统计信息
|
// GetStats 获取兑换码统计信息
|
||||||
func (s *RedeemService) GetStats(ctx context.Context) (map[string]interface{}, error) {
|
func (s *RedeemService) GetStats(ctx context.Context) (map[string]any, error) {
|
||||||
// TODO: 实现统计逻辑
|
// TODO: 实现统计逻辑
|
||||||
// 统计未使用、已使用的兑换码数量
|
// 统计未使用、已使用的兑换码数量
|
||||||
// 统计总面值等
|
// 统计总面值等
|
||||||
|
|
||||||
stats := map[string]interface{}{
|
stats := map[string]any{
|
||||||
"total_codes": 0,
|
"total_codes": 0,
|
||||||
"unused_codes": 0,
|
"unused_codes": 0,
|
||||||
"used_codes": 0,
|
"used_codes": 0,
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ type TokenRefresher interface {
|
|||||||
|
|
||||||
// Refresh 执行token刷新,返回更新后的credentials
|
// Refresh 执行token刷新,返回更新后的credentials
|
||||||
// 注意:返回的map应该保留原有credentials中的所有字段,只更新token相关字段
|
// 注意:返回的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刷新
|
// ClaudeTokenRefresher 处理Anthropic/Claude OAuth token刷新
|
||||||
@@ -61,14 +61,14 @@ func (r *ClaudeTokenRefresher) NeedsRefresh(account *model.Account, refreshWindo
|
|||||||
|
|
||||||
// Refresh 执行token刷新
|
// Refresh 执行token刷新
|
||||||
// 保留原有credentials中的所有字段,只更新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)
|
tokenInfo, err := r.oauthService.RefreshAccountToken(ctx, account)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// 保留现有credentials中的所有字段
|
// 保留现有credentials中的所有字段
|
||||||
newCredentials := make(map[string]interface{})
|
newCredentials := make(map[string]any)
|
||||||
for k, v := range account.Credentials {
|
for k, v := range account.Credentials {
|
||||||
newCredentials[k] = v
|
newCredentials[k] = v
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -195,7 +195,7 @@ func (s *UsageService) GetStatsByModel(ctx context.Context, modelName string, st
|
|||||||
}
|
}
|
||||||
|
|
||||||
// GetDailyStats 获取每日使用统计(最近N天)
|
// 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()
|
endTime := time.Now()
|
||||||
startTime := endTime.AddDate(0, 0, -days)
|
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 {
|
for date, stats := range dailyStats {
|
||||||
if stats.TotalRequests > 0 {
|
if stats.TotalRequests > 0 {
|
||||||
stats.AverageDurationMs /= float64(stats.TotalRequests)
|
stats.AverageDurationMs /= float64(stats.TotalRequests)
|
||||||
}
|
}
|
||||||
|
|
||||||
result = append(result, map[string]interface{}{
|
result = append(result, map[string]any{
|
||||||
"date": date,
|
"date": date,
|
||||||
"total_requests": stats.TotalRequests,
|
"total_requests": stats.TotalRequests,
|
||||||
"total_input_tokens": stats.TotalInputTokens,
|
"total_input_tokens": stats.TotalInputTokens,
|
||||||
|
|||||||
Reference in New Issue
Block a user