diff --git a/common/custom-event.go b/common/custom-event.go index fd8fee87cb..3521293e9b 100644 --- a/common/custom-event.go +++ b/common/custom-event.go @@ -53,7 +53,7 @@ type CustomEvent struct { Event string Id string Retry uint - Data interface{} + Data any } func encode(writer io.Writer, event CustomEvent) error { @@ -61,7 +61,7 @@ func encode(writer io.Writer, event CustomEvent) error { return writeData(w, event.Data) } -func writeData(w stringWriter, data interface{}) error { +func writeData(w stringWriter, data any) error { dataReplacer.WriteString(w, fmt.Sprint(data)) if strings.HasPrefix(data.(string), "data") { w.writeString("\n\n") diff --git a/common/etag.go b/common/etag.go index cbae5a5865..9b55e621f3 100644 --- a/common/etag.go +++ b/common/etag.go @@ -10,7 +10,7 @@ import ( type digestAnchor struct{} func modulePath() string { - return reflect.TypeOf(digestAnchor{}).PkgPath() + return reflect.TypeFor[digestAnchor]().PkgPath() } var digestSeed = func() (s [sha256.Size]byte) { diff --git a/common/gopool.go b/common/gopool.go index d410380b86..370a59adb5 100644 --- a/common/gopool.go +++ b/common/gopool.go @@ -12,7 +12,7 @@ var relayGoPool gopool.Pool func init() { relayGoPool = gopool.NewPool("gopool.RelayPool", math.MaxInt32, gopool.NewConfig()) - relayGoPool.SetPanicHandler(func(ctx context.Context, i interface{}) { + relayGoPool.SetPanicHandler(func(ctx context.Context, i any) { if stopChan, ok := ctx.Value("stop_chan").(chan bool); ok { SafeSendBool(stopChan, true) } diff --git a/common/init.go b/common/init.go index 9704f9955a..b34f4376d8 100644 --- a/common/init.go +++ b/common/init.go @@ -213,8 +213,8 @@ func initConstantEnv() { soraPatchStr := GetEnvOrDefaultString("TASK_PRICE_PATCH", "") if soraPatchStr != "" { var taskPricePatches []string - soraPatches := strings.Split(soraPatchStr, ",") - for _, patch := range soraPatches { + soraPatches := strings.SplitSeq(soraPatchStr, ",") + for patch := range soraPatches { trimmedPatch := strings.TrimSpace(patch) if trimmedPatch != "" { taskPricePatches = append(taskPricePatches, trimmedPatch) @@ -226,8 +226,8 @@ func initConstantEnv() { // Initialize trusted redirect domains for URL validation trustedDomainsStr := GetEnvOrDefaultString("TRUSTED_REDIRECT_DOMAINS", "") var trustedDomains []string - domains := strings.Split(trustedDomainsStr, ",") - for _, domain := range domains { + domains := strings.SplitSeq(trustedDomainsStr, ",") + for domain := range domains { trimmedDomain := strings.TrimSpace(domain) if trimmedDomain != "" { // Normalize domain to lowercase diff --git a/common/quota_math.go b/common/quota_math.go index fb0e71caa6..e658974a9b 100644 --- a/common/quota_math.go +++ b/common/quota_math.go @@ -59,11 +59,11 @@ func (c *QuotaClamp) Error() string { // AuditMap renders the clamp as the marker stored under a log's // admin_info.quota_saturation. Centralized here so every billing path (consume // logs, task billing logs, task compensation logs) records the same shape. -func (c *QuotaClamp) AuditMap() map[string]interface{} { +func (c *QuotaClamp) AuditMap() map[string]any { if c == nil { return nil } - return map[string]interface{}{ + return map[string]any{ "op": c.Op, "kind": c.Kind, "original": c.Original, diff --git a/common/redis.go b/common/redis.go index c72878378f..aef7fc743c 100644 --- a/common/redis.go +++ b/common/redis.go @@ -104,13 +104,13 @@ func RedisDelKey(key string) error { return RDB.Del(ctx, key).Err() } -func RedisHSetObj(key string, obj interface{}, expiration time.Duration) error { +func RedisHSetObj(key string, obj any, expiration time.Duration) error { if DebugEnabled { SysLog(fmt.Sprintf("Redis HSET: key=%s, obj=%+v, expiration=%v", key, obj, expiration)) } ctx := context.Background() - data := make(map[string]interface{}) + data := make(map[string]any) // 使用反射遍历结构体字段 v := reflect.ValueOf(obj).Elem() @@ -125,7 +125,7 @@ func RedisHSetObj(key string, obj interface{}, expiration time.Duration) error { } // 处理指针类型 - if value.Kind() == reflect.Ptr { + if value.Kind() == reflect.Pointer { if value.IsNil() { data[field.Name] = "" continue @@ -158,7 +158,7 @@ func RedisHSetObj(key string, obj interface{}, expiration time.Duration) error { return nil } -func RedisHGetObj(key string, obj interface{}) error { +func RedisHGetObj(key string, obj any) error { if DebugEnabled { SysLog(fmt.Sprintf("Redis HGETALL: key=%s", key)) } @@ -175,7 +175,7 @@ func RedisHGetObj(key string, obj interface{}) error { // Handle both pointer and non-pointer values val := reflect.ValueOf(obj) - if val.Kind() != reflect.Ptr { + if val.Kind() != reflect.Pointer { return fmt.Errorf("obj must be a pointer to a struct, got %T", obj) } @@ -192,7 +192,7 @@ func RedisHGetObj(key string, obj interface{}) error { fieldValue := v.Field(i) // Handle pointer types - if fieldValue.Kind() == reflect.Ptr { + if fieldValue.Kind() == reflect.Pointer { if value == "" { continue } @@ -299,7 +299,7 @@ func RedisHIncrBy(key, field string, delta int64) error { return nil } -func RedisHSetField(key, field string, value interface{}) error { +func RedisHSetField(key, field string, value any) error { if DebugEnabled { SysLog(fmt.Sprintf("Redis HSET field: key=%s, field=%s, value=%v", key, field, value)) } diff --git a/common/session_cookie.go b/common/session_cookie.go index 28981ce9d8..9f328d4f27 100644 --- a/common/session_cookie.go +++ b/common/session_cookie.go @@ -63,8 +63,8 @@ func InitSessionCookieSettings() error { return fmt.Errorf("SESSION_COOKIE_SECURE=true requires SESSION_COOKIE_TRUSTED_URL") } - trustedURLs := strings.Split(trustedURLsRaw, ",") - for _, trustedURL := range trustedURLs { + trustedURLs := strings.SplitSeq(trustedURLsRaw, ",") + for trustedURL := range trustedURLs { trustedURL = strings.TrimSpace(trustedURL) if trustedURL == "" { return fmt.Errorf("SESSION_COOKIE_TRUSTED_URL contains an empty URL") diff --git a/common/ssrf_protection.go b/common/ssrf_protection.go index f42e9435da..23a9512140 100644 --- a/common/ssrf_protection.go +++ b/common/ssrf_protection.go @@ -4,6 +4,7 @@ import ( "fmt" "net" "net/url" + "slices" "strconv" "strings" ) @@ -197,12 +198,7 @@ func (p *SSRFProtection) isAllowedPort(port int) bool { return true // 如果没有配置端口限制,则允许所有端口 } - for _, allowedPort := range p.AllowedPorts { - if port == allowedPort { - return true - } - } - return false + return slices.Contains(p.AllowedPorts, port) } // isDomainWhitelisted 检查域名是否在白名单中 @@ -222,8 +218,8 @@ func isDomainListed(domain string, list []string) bool { return true } // 通配符匹配 (*.example.com) - if strings.HasPrefix(item, "*.") { - suffix := strings.TrimPrefix(item, "*.") + if after, ok := strings.CutPrefix(item, "*."); ok { + suffix := after if strings.HasSuffix(domain, "."+suffix) || domain == suffix { return true } diff --git a/common/str.go b/common/str.go index b412c7dc11..cffe228b85 100644 --- a/common/str.go +++ b/common/str.go @@ -4,11 +4,13 @@ import ( "encoding/base64" "encoding/json" "fmt" - kitutil "github.com/QuantumNous/new-api/relaykit/relayconvert/kitutil" + "slices" "strconv" "strings" "unsafe" + kitutil "github.com/QuantumNous/new-api/relaykit/relayconvert/kitutil" + "github.com/samber/lo" ) @@ -36,7 +38,7 @@ func GetRandomString(length int) string { return lo.RandomString(length, lo.AlphanumericCharset) } -func MapToJsonStr(m map[string]interface{}) string { +func MapToJsonStr(m map[string]any) string { bytes, err := json.Marshal(m) if err != nil { return "" @@ -44,8 +46,8 @@ func MapToJsonStr(m map[string]interface{}) string { return string(bytes) } -func StrToMap(str string) (map[string]interface{}, error) { - m := make(map[string]interface{}) +func StrToMap(str string) (map[string]any, error) { + m := make(map[string]any) err := Unmarshal([]byte(str), &m) if err != nil { return nil, err @@ -53,8 +55,8 @@ func StrToMap(str string) (map[string]interface{}, error) { return m, nil } -func StrToJsonArray(str string) ([]interface{}, error) { - var js []interface{} +func StrToJsonArray(str string) ([]any, error) { + var js []any err := json.Unmarshal([]byte(str), &js) if err != nil { return nil, err @@ -63,12 +65,12 @@ func StrToJsonArray(str string) ([]interface{}, error) { } func IsJsonArray(str string) bool { - var js []interface{} + var js []any return json.Unmarshal([]byte(str), &js) == nil } func IsJsonObject(str string) bool { - var js map[string]interface{} + var js map[string]any return json.Unmarshal([]byte(str), &js) == nil } @@ -81,12 +83,7 @@ func String2Int(str string) int { } func StringsContains(strs []string, str string) bool { - for _, s := range strs { - if s == str { - return true - } - } - return false + return slices.Contains(strs, str) } // StringToByteSlice []byte only read, panic on append @@ -126,14 +123,14 @@ func MaskEmail(email string) string { } // Find the @ symbol - atIndex := strings.Index(email, "@") - if atIndex == -1 { + _, after, ok := strings.Cut(email, "@") + if !ok { // No @ symbol found, return masked return "***masked***" } // Return only the domain part with @ symbol - return "***@" + email[atIndex+1:] + return "***@" + after } // MaskSensitiveInfo moved to the conversion kit (kitutil) because the types diff --git a/common/totp.go b/common/totp.go index 400f9d05c5..e772fa2239 100644 --- a/common/totp.go +++ b/common/totp.go @@ -49,7 +49,7 @@ func ValidateTOTPCode(secret, code string) bool { func GenerateBackupCodes() ([]string, error) { codes := make([]string, BackupCodeCount) - for i := 0; i < BackupCodeCount; i++ { + for i := range BackupCodeCount { code, err := generateRandomBackupCode() if err != nil { return nil, err diff --git a/common/utils.go b/common/utils.go index 7e658ff4ea..4850d85ef3 100644 --- a/common/utils.go +++ b/common/utils.go @@ -188,7 +188,7 @@ func Seconds2Time(num int) (time string) { return } -func Interface2String(inter interface{}) string { +func Interface2String(inter any) string { switch inter.(type) { case string: return inter.(string) @@ -208,7 +208,7 @@ func Interface2String(inter interface{}) string { return fmt.Sprintf("%v", inter) } -func UnescapeHTML(x string) interface{} { +func UnescapeHTML(x string) any { return template.HTML(x) } diff --git a/controller/access_token.go b/controller/access_token.go index b47b11875f..8614115f82 100644 --- a/controller/access_token.go +++ b/controller/access_token.go @@ -44,7 +44,7 @@ func GenerateAccessToken(c *gin.Context) { writeSecurityOperationError(c, err) return } - recordUserSecurityAudit(c, id, "access_token.generate", map[string]interface{}{"token_ref": model.AccessTokenFingerprint(key)}) + recordUserSecurityAudit(c, id, "access_token.generate", map[string]any{"token_ref": model.AccessTokenFingerprint(key)}) c.JSON(http.StatusOK, gin.H{"success": true, "message": "", "data": key}) } @@ -58,7 +58,7 @@ func RevokeAccessToken(c *gin.Context) { return } if ref != "" { - recordUserSecurityAudit(c, c.GetInt("id"), "access_token.revoke", map[string]interface{}{"token_ref": ref}) + recordUserSecurityAudit(c, c.GetInt("id"), "access_token.revoke", map[string]any{"token_ref": ref}) } common.ApiSuccess(c, nil) } diff --git a/controller/access_token_audit_test.go b/controller/access_token_audit_test.go index f5057820db..cc06aa21cb 100644 --- a/controller/access_token_audit_test.go +++ b/controller/access_token_audit_test.go @@ -4,8 +4,6 @@ import ( "context" "errors" "fmt" - sqlmysql "github.com/go-sql-driver/mysql" - "gorm.io/driver/clickhouse" "net" "net/http" "net/http/httptest" @@ -15,6 +13,9 @@ import ( "testing" "time" + sqlmysql "github.com/go-sql-driver/mysql" + "gorm.io/driver/clickhouse" + "github.com/QuantumNous/new-api/common" "github.com/QuantumNous/new-api/middleware" "github.com/QuantumNous/new-api/model" @@ -128,7 +129,7 @@ func TestAccessTokenAuditsResultsAndExcludesBrowserSessions(t *testing.T) { router.GET("/rate-limited", func(c *gin.Context) { c.AbortWithStatusJSON(429, gin.H{"success": false}) }, middleware.UserAuth()) router.GET("/read/:id", middleware.UserAuth(), func(c *gin.Context) { c.JSON(200, gin.H{"success": true}) }) router.POST("/write", middleware.AdminAuth(), func(c *gin.Context) { - recordManageAudit(c, "option.update", map[string]interface{}{"key": "safe-setting"}) + recordManageAudit(c, "option.update", map[string]any{"key": "safe-setting"}) c.JSON(200, gin.H{"success": true}) }) router.POST("/business-failure", middleware.AdminAuth(), func(c *gin.Context) { c.JSON(200, gin.H{"success": false, "message": "secret-response"}) }) @@ -202,7 +203,7 @@ func TestAuditIsolationVisibilityAndFailureContracts(t *testing.T) { var payload struct { Data struct { Items []struct { - Other map[string]interface{} `json:"other"` + Other map[string]any `json:"other"` } } } @@ -343,7 +344,7 @@ func TestSecurityAndOperationEventsUseAuditTable(t *testing.T) { for _, action := range []string{"user.passkey_register", "user.passkey_delete", "user.2fa_setup", "user.2fa_enable", "user.2fa_disable_self", "user.2fa_backup_codes", "user.security_verify"} { recordUserSecurityAudit(c, user.Id, action, nil) } - recordManageAudit(c, "option.update", map[string]interface{}{"key": "safe"}) + recordManageAudit(c, "option.update", map[string]any{"key": "safe"}) recordSubscriptionResetUserLogs(c, &model.SubscriptionResetResult{ResetCount: 1, PlanId: 1, PlanTitle: "Plan", AffectedUserIds: []int{user.Id}}, &model.AuditAdminInfo{AdminID: user.Id}) for _, typ := range []int{model.LogTypeTopup, model.LogTypeConsume, model.LogTypeRefund, model.LogTypeSystem} { model.RecordLog(user.Id, typ, "business entry") @@ -536,7 +537,7 @@ func verifyAuditJSONStorage(t *testing.T) { metadata := model.AuditOther{ Op: &model.AuditOperation{Action: "channel.update", Params: model.AuditFields{ "id": 42, "name": "渠道", "changed_fields": []string{}, "large_id": uint64(9007199254740993), - "extra": map[string]interface{}{"attempts": 0, "permitted": false, "ratio": 1.25, "targets": []int{1, 2}}, + "extra": map[string]any{"attempts": 0, "permitted": false, "ratio": 1.25, "targets": []int{1, 2}}, }}, AdminInfo: &model.AuditAdminInfo{AdminID: 1}, AuditInfo: &model.AuditRequestInfo{Method: "PUT", Route: "/api/channel/", Path: "/api/channel/", Status: 200, Success: false}, @@ -586,7 +587,7 @@ func verifyAuditJSONStorage(t *testing.T) { empty, err := common.Marshal(entries[0].Other) require.NoError(t, err) assert.JSONEq(t, `{}`, string(empty)) - for i := 0; i < 2; i++ { + for range 2 { require.NoError(t, model.InitLogDB()) } entries, total, err = model.GetAuditLogs(filter, 0, 20, common.RoleRootUser) @@ -600,7 +601,7 @@ func verifyAuditJSONStorage(t *testing.T) { func TestAuditOtherDatabaseEncoding(t *testing.T) { const payload = `{"op":{"action":"channel.update","params":{"id":9007199254740993,"nested":{"count":0,"enabled":false}}},"admin_info":{"admin_id":1,"admin_username":"root","admin_role":100,"auth_method":"session"},"audit_info":{"method":"PUT","route":"/api/channel/","path":"/api/channel/","status":200,"success":false},"root_info":{"generation":18446744073709551615}}` - for _, input := range []interface{}{payload, []byte(payload)} { + for _, input := range []any{payload, []byte(payload)} { var other model.AuditOther require.NoError(t, other.Scan(input)) require.NotNil(t, other.Op) @@ -616,7 +617,7 @@ func TestAuditOtherDatabaseEncoding(t *testing.T) { assert.JSONEq(t, payload, text) assert.Contains(t, text, "9007199254740993") assert.Contains(t, text, "18446744073709551615") - for _, empty := range []interface{}{nil, "", []byte(`null`), "{}"} { + for _, empty := range []any{nil, "", []byte(`null`), "{}"} { require.NoError(t, other.Scan(input)) require.NoError(t, other.Scan(empty)) encoded, err = other.Value() @@ -679,7 +680,7 @@ func TestAuditDatabaseMatrix(t *testing.T) { require.NoError(t, db.Create(&releasedAuditUser{Username: "released-owner", Password: "placeholder", AccessToken: &legacy, AffCode: "released-aff", Quota: 1234}).Error) require.NoError(t, db.Create(&releasedAuditLog{UserId: 1, Type: model.LogTypeLogin, Content: "historical login", CreatedAt: 100, RequestId: "legacy-request"}).Error) } - for i := 0; i < 2; i++ { + for range 2 { require.NoError(t, model.InitDB()) require.NoError(t, model.InitLogDB()) } diff --git a/controller/audit.go b/controller/audit.go index d9b2b85d53..d9c5bc411e 100644 --- a/controller/audit.go +++ b/controller/audit.go @@ -66,7 +66,7 @@ var auditContentTemplates = map[string]string{ } // auditContentEN 按 action 模板渲染英文兜底文本;未登记的 action 退回 action 本身。 -func auditContentEN(action string, params map[string]interface{}) string { +func auditContentEN(action string, params map[string]any) string { tmpl, ok := auditContentTemplates[action] if !ok { return action @@ -104,15 +104,15 @@ func markAuditLogged(c *gin.Context) { // recordManageAudit 记录一条由操作者本人归属的管理/高危审计日志(资源类操作: // 渠道 / 系统设置 / 兑换码等)。content 由 action+params 自动渲染。 -func recordManageAudit(c *gin.Context, action string, params map[string]interface{}) { +func recordManageAudit(c *gin.Context, action string, params map[string]any) { recordManageAuditFor(c, c.GetInt("id"), action, params) } // recordManageAuditFor 记录一条管理审计日志,日志归属于操作者;targetUserId // 只表示被操作用户,用于在结构化参数中保留目标上下文。 -func recordManageAuditFor(c *gin.Context, targetUserId int, action string, params map[string]interface{}) { +func recordManageAuditFor(c *gin.Context, targetUserId int, action string, params map[string]any) { if params == nil { - params = map[string]interface{}{} + params = map[string]any{} } operatorUserId := c.GetInt("id") if _, ok := params["target_user_id"]; !ok && targetUserId > 0 && targetUserId != operatorUserId { @@ -124,10 +124,10 @@ func recordManageAuditFor(c *gin.Context, targetUserId int, action string, param // recordUserSecurityAudit 记录普通用户自己的安全敏感操作(如 passkey 绑定/解绑)。 // 这类日志没有管理员操作者,不写 admin_info;同时不依赖 AdminAuth/RootAuth 的兜底。 -func recordUserSecurityAudit(c *gin.Context, userId int, action string, params map[string]interface{}) { +func recordUserSecurityAudit(c *gin.Context, userId int, action string, params map[string]any) { if code := c.GetString("security_error_code"); code != "" { if params == nil { - params = map[string]interface{}{} + params = map[string]any{} } params["code"] = code } diff --git a/controller/auth_flow_test.go b/controller/auth_flow_test.go index 468cfd6aa6..b8c9030c91 100644 --- a/controller/auth_flow_test.go +++ b/controller/auth_flow_test.go @@ -92,7 +92,7 @@ func TestSecurityLoginCodeCompletesOnce(t *testing.T) { router := gin.New() router.POST("/api/user/login/verify", VerifyLogin) router.POST("/api/user/login/2fa", Verify2FALogin) - for attempt := 0; attempt < 2; attempt++ { + for attempt := range 2 { response := httptest.NewRecorder() router.ServeHTTP(response, httptest.NewRequest("POST", test.path, strings.NewReader(string(body)))) var result securityEnrollmentResponse @@ -241,12 +241,10 @@ func TestSecurityLoginPasskeyConcurrentCompletionCreatesOneSession(t *testing.T) responses := make(chan *httptest.ResponseRecorder, 2) var workers sync.WaitGroup for _, body := range requests { - workers.Add(1) - go func() { - defer workers.Done() + workers.Go(func() { <-start responses <- securityEnrollmentRequest("POST", "/api/user/login/passkey/finish", body, "", service.AuthIdentity{}, LoginPasskeyFinish) - }() + }) } close(start) workers.Wait() diff --git a/controller/channel-test.go b/controller/channel-test.go index f8fad94cd2..1248853a51 100644 --- a/controller/channel-test.go +++ b/controller/channel-test.go @@ -613,7 +613,7 @@ func detectErrorFromTestResponseBody(respBody []byte) error { return fmt.Errorf("upstream error: %s", message) } - for _, line := range bytes.Split(b, []byte{'\n'}) { + for line := range bytes.SplitSeq(b, []byte{'\n'}) { line = bytes.TrimSpace(line) if len(line) == 0 { continue @@ -639,7 +639,7 @@ func validateStreamTestResponseBody(respBody []byte) error { return errors.New("stream response body is empty") } - for _, line := range bytes.Split(b, []byte{'\n'}) { + for line := range bytes.SplitSeq(b, []byte{'\n'}) { line = bytes.TrimSpace(line) if len(line) == 0 || !bytes.HasPrefix(line, []byte("data:")) { continue diff --git a/controller/channel.go b/controller/channel.go index b77e97d45b..b0bde66f61 100644 --- a/controller/channel.go +++ b/controller/channel.go @@ -369,14 +369,8 @@ func SearchChannels(c *gin.Context) { } total := len(channelData) - startIdx := (page - 1) * pageSize - if startIdx > total { - startIdx = total - } - endIdx := startIdx + pageSize - if endIdx > total { - endIdx = total - } + startIdx := min((page-1)*pageSize, total) + endIdx := min(startIdx+pageSize, total) pagedData := channelData[startIdx:endIdx] @@ -439,7 +433,7 @@ func GetChannelKey(c *gin.Context) { } // 记录操作审计日志(高危:查看渠道密钥) - recordManageAudit(c, "channel.key_view", map[string]interface{}{ + recordManageAudit(c, "channel.key_view", map[string]any{ "id": channelId, "name": channel.Name, }) @@ -448,7 +442,7 @@ func GetChannelKey(c *gin.Context) { c.JSON(http.StatusOK, gin.H{ "success": true, "message": "获取成功", - "data": map[string]interface{}{ + "data": map[string]any{ "key": channel.Key, }, }) @@ -588,7 +582,7 @@ func getVertexArrayKeys(keys string) ([]string, error) { if keys == "" { return nil, nil } - var keyArray []interface{} + var keyArray []any err := common.Unmarshal([]byte(keys), &keyArray) if err != nil { return nil, fmt.Errorf("批量添加 Vertex AI 必须使用标准的JsonArray格式,例如[{key1}, {key2}...],请检查输入: %w", err) @@ -664,7 +658,7 @@ func AddChannel(c *gin.Context) { addChannelRequest.Channel.Key = strings.Join(array, "\n") } else { cleanKeys := make([]string, 0) - for _, key := range strings.Split(addChannelRequest.Channel.Key, "\n") { + for key := range strings.SplitSeq(addChannelRequest.Channel.Key, "\n") { if key == "" { continue } @@ -720,7 +714,7 @@ func AddChannel(c *gin.Context) { common.ApiError(c, err) return } - createAudit := map[string]interface{}{ + createAudit := map[string]any{ "name": addChannelRequest.Channel.Name, "type": addChannelRequest.Channel.Type, "count": len(channels), @@ -759,7 +753,7 @@ func DeleteChannel(c *gin.Context) { } else { service.InvalidateProxyClient(channelProxy) } - recordManageAudit(c, "channel.delete", map[string]interface{}{ + recordManageAudit(c, "channel.delete", map[string]any{ "id": id, "name": channelName, }) @@ -780,7 +774,7 @@ func DeleteDisabledChannel(c *gin.Context) { if rows > 0 { service.ResetProxyClientCache() } - recordManageAudit(c, "channel.delete_disabled", map[string]interface{}{ + recordManageAudit(c, "channel.delete_disabled", map[string]any{ "count": rows, }) c.JSON(http.StatusOK, gin.H{ @@ -819,7 +813,7 @@ func DisableTagChannels(c *gin.Context) { return } model.InitChannelCache() - recordManageAudit(c, "channel.tag_disable", map[string]interface{}{ + recordManageAudit(c, "channel.tag_disable", map[string]any{ "tag": channelTag.Tag, }) c.JSON(http.StatusOK, gin.H{ @@ -845,7 +839,7 @@ func EnableTagChannels(c *gin.Context) { return } model.InitChannelCache() - recordManageAudit(c, "channel.tag_enable", map[string]interface{}{ + recordManageAudit(c, "channel.tag_enable", map[string]any{ "tag": channelTag.Tag, }) c.JSON(http.StatusOK, gin.H{ @@ -905,7 +899,7 @@ func EditTagChannels(c *gin.Context) { return } model.InitChannelCache() - recordManageAudit(c, "channel.tag_edit", map[string]interface{}{ + recordManageAudit(c, "channel.tag_edit", map[string]any{ "tag": channelTag.Tag, }) c.JSON(http.StatusOK, gin.H{ @@ -939,7 +933,7 @@ func DeleteChannelBatch(c *gin.Context) { if deletedCount > 0 { service.ResetProxyClientCache() } - recordManageAudit(c, "channel.delete_batch", map[string]interface{}{ + recordManageAudit(c, "channel.delete_batch", map[string]any{ "count": deletedCount, }) c.JSON(http.StatusOK, gin.H{ @@ -1080,8 +1074,8 @@ func UpdateChannel(c *gin.Context) { } } else { // 普通渠道的处理 - inputKeys := strings.Split(channel.Key, "\n") - for _, key := range inputKeys { + inputKeys := strings.SplitSeq(channel.Key, "\n") + for key := range inputKeys { key = strings.TrimSpace(key) if key != "" { newKeys = append(newKeys, key) @@ -1143,7 +1137,7 @@ func UpdateChannel(c *gin.Context) { if channel.Key != "" && channel.Key != originChannel.Key { changedFields = append(changedFields, "key") } - updateAudit := map[string]interface{}{ + updateAudit := map[string]any{ "id": channel.Id, "name": channel.Name, "changed_fields": changedFields, @@ -1177,7 +1171,7 @@ func UpdateChannelStatus(c *gin.Context) { if changed { model.InitChannelCache() } - recordManageAudit(c, "channel.status_update", map[string]interface{}{ + recordManageAudit(c, "channel.status_update", map[string]any{ "id": id, "status": req.Status, "changed": changed, @@ -1204,7 +1198,7 @@ func BatchUpdateChannelStatus(c *gin.Context) { if changedCount > 0 { model.InitChannelCache() } - recordManageAudit(c, "channel.status_update_batch", map[string]interface{}{ + recordManageAudit(c, "channel.status_update_batch", map[string]any{ "count": changedCount, "total": len(req.Ids), "status": req.Status, @@ -1382,7 +1376,7 @@ func BatchSetChannelTag(c *gin.Context) { return } model.InitChannelCache() - recordManageAudit(c, "channel.tag_batch_set", map[string]interface{}{ + recordManageAudit(c, "channel.tag_batch_set", map[string]any{ "count": len(channelBatch.Ids), }) c.JSON(http.StatusOK, gin.H{ @@ -1493,7 +1487,7 @@ func CopyChannel(c *gin.Context) { return } model.InitChannelCache() - recordManageAudit(c, "channel.copy", map[string]interface{}{ + recordManageAudit(c, "channel.copy", map[string]any{ "sourceId": id, "id": clone.Id, "name": clone.Name, @@ -1568,7 +1562,7 @@ func ManageMultiKeys(c *gin.Context) { if request.Action == "get_key_status" { markAuditLogged(c) } else { - recordManageAudit(c, "channel.multi_key_manage", map[string]interface{}{ + recordManageAudit(c, "channel.multi_key_manage", map[string]any{ "action": request.Action, "id": channel.Id, }) @@ -1666,10 +1660,7 @@ func ManageMultiKeys(c *gin.Context) { // Calculate range for current page start := (page - 1) * pageSize - end := start + pageSize - if end > filteredTotal { - end = filteredTotal - } + end := min(start+pageSize, filteredTotal) // Get the page data var pageKeyStatusList []KeyStatus diff --git a/controller/channel_authz_test.go b/controller/channel_authz_test.go index 0a57eac50d..66e47b0446 100644 --- a/controller/channel_authz_test.go +++ b/controller/channel_authz_test.go @@ -197,7 +197,7 @@ func TestChannelFieldsAreClassified(t *testing.T) { return names } - for _, name := range collect(reflect.TypeOf(PatchChannel{})) { + for _, name := range collect(reflect.TypeFor[PatchChannel]()) { assert.Truef(t, classified(name), "channel field %q is not classified; add it to channelSensitiveFields, channelNonSensitiveFields, channelOperationalFields, or channelReadOnlyFields in channel_authz.go", name) } diff --git a/controller/channel_upstream_update.go b/controller/channel_upstream_update.go index 6817a0086a..ef1b6debc7 100644 --- a/controller/channel_upstream_update.go +++ b/controller/channel_upstream_update.go @@ -498,7 +498,7 @@ func fetchAdvancedCustomUpstreamModelIDs(channel *model.Channel, baseURL string) func updateChannelUpstreamModelSettings(channel *model.Channel, settings dto.ChannelOtherSettings, updateModels bool) error { channel.SetOtherSettings(settings) - updates := map[string]interface{}{ + updates := map[string]any{ "settings": channel.OtherSettings, } if updateModels { @@ -889,7 +889,7 @@ func ApplyChannelUpstreamModelUpdates(c *gin.Context) { refreshChannelRuntimeCache() } - recordManageAudit(c, "channel.upstream_apply", map[string]interface{}{ + recordManageAudit(c, "channel.upstream_apply", map[string]any{ "id": channel.Id, }) c.JSON(http.StatusOK, gin.H{ @@ -1087,7 +1087,7 @@ func ApplyAllChannelUpstreamModelUpdates(c *gin.Context) { refreshChannelRuntimeCache() } - recordManageAudit(c, "channel.upstream_apply_all", map[string]interface{}{ + recordManageAudit(c, "channel.upstream_apply_all", map[string]any{ "count": len(results), }) c.JSON(http.StatusOK, gin.H{ @@ -1128,7 +1128,7 @@ func DetectAllChannelUpstreamModelUpdates(c *gin.Context) { return } - recordManageAudit(c, "channel.upstream_detect_all", map[string]interface{}{ + recordManageAudit(c, "channel.upstream_detect_all", map[string]any{ "task_id": task.TaskID, }) c.JSON(http.StatusOK, gin.H{ diff --git a/controller/channel_upstream_update_test.go b/controller/channel_upstream_update_test.go index 5cb4fac4b0..9948d00817 100644 --- a/controller/channel_upstream_update_test.go +++ b/controller/channel_upstream_update_test.go @@ -534,7 +534,7 @@ func TestCollectPendingUpstreamModelChangesFromModels_WithIgnoredRegexPatterns(t func TestBuildUpstreamModelUpdateTaskNotificationContent_OmitOverflowDetails(t *testing.T) { channelSummaries := make([]upstreamModelUpdateChannelSummary, 0, 12) - for i := 0; i < 12; i++ { + for i := range 12 { channelSummaries = append(channelSummaries, upstreamModelUpdateChannelSummary{ ChannelName: "channel-" + string(rune('A'+i)), AddCount: i + 1, diff --git a/controller/custom_oauth.go b/controller/custom_oauth.go index 4aed8ad405..ff448a423b 100644 --- a/controller/custom_oauth.go +++ b/controller/custom_oauth.go @@ -538,7 +538,7 @@ func UnbindCustomOAuth(c *gin.Context) { succeeded, notificationFailed := false, false defer func() { - recordUserSecurityAudit(c, identity.UserID, "user.binding_unbind", map[string]interface{}{"provider_id": providerId, "success": succeeded, "notification_failed": notificationFailed}) + recordUserSecurityAudit(c, identity.UserID, "user.binding_unbind", map[string]any{"provider_id": providerId, "success": succeeded, "notification_failed": notificationFailed}) }() context, err := common.Marshal(service.AccountUnbindingContext{ProviderID: providerId}) if err != nil { diff --git a/controller/deployment.go b/controller/deployment.go index a2ffedc667..6dc51149ea 100644 --- a/controller/deployment.go +++ b/controller/deployment.go @@ -135,7 +135,7 @@ func requireContainerID(c *gin.Context) (string, bool) { return containerID, true } -func mapIoNetDeployment(d ionet.Deployment) map[string]interface{} { +func mapIoNetDeployment(d ionet.Deployment) map[string]any { var created int64 if d.CreatedAt.IsZero() { created = time.Now().Unix() @@ -156,7 +156,7 @@ func mapIoNetDeployment(d ionet.Deployment) map[string]interface{} { hardwareInfo := fmt.Sprintf("%s %s x%d", d.BrandName, d.HardwareName, d.HardwareQuantity) - return map[string]interface{}{ + return map[string]any{ "id": d.ID, "deployment_name": d.Name, "container_name": d.Name, @@ -176,7 +176,7 @@ func mapIoNetDeployment(d ionet.Deployment) map[string]interface{} { "model_name": "", "model_version": "", "instance_count": d.HardwareQuantity, - "resource_config": map[string]interface{}{ + "resource_config": map[string]any{ "cpu": "", "memory": "", "gpu": strconv.Itoa(d.HardwareQuantity), @@ -225,7 +225,7 @@ func GetAllDeployments(c *gin.Context) { return } - items := make([]map[string]interface{}, 0, len(dl.Deployments)) + items := make([]map[string]any, 0, len(dl.Deployments)) for _, d := range dl.Deployments { items = append(items, mapIoNetDeployment(d)) } @@ -274,7 +274,7 @@ func SearchDeployments(c *gin.Context) { } } - items := make([]map[string]interface{}, 0, len(filtered)) + items := make([]map[string]any, 0, len(filtered)) for _, d := range filtered { items = append(items, mapIoNetDeployment(d)) } @@ -310,7 +310,7 @@ func GetDeployment(c *gin.Context) { return } - data := map[string]interface{}{ + data := map[string]any{ "id": details.ID, "deployment_name": details.ID, "model_name": "", @@ -318,7 +318,7 @@ func GetDeployment(c *gin.Context) { "status": strings.ToLower(details.Status), "instance_count": details.TotalContainers, "hardware_id": details.HardwareID, - "resource_config": map[string]interface{}{ + "resource_config": map[string]any{ "cpu": "", "memory": "", "gpu": strconv.Itoa(details.TotalGPUs), @@ -668,10 +668,7 @@ func GetDeploymentLogs(c *gin.Context) { var limit int = 100 if limitStr != "" { if parsedLimit, err := strconv.Atoi(limitStr); err == nil && parsedLimit > 0 { - limit = parsedLimit - if limit > 1000 { - limit = 1000 - } + limit = min(parsedLimit, 1000) } } @@ -720,19 +717,19 @@ func ListDeploymentContainers(c *gin.Context) { return } - items := make([]map[string]interface{}, 0) + items := make([]map[string]any, 0) if containers != nil { - items = make([]map[string]interface{}, 0, len(containers.Workers)) + items = make([]map[string]any, 0, len(containers.Workers)) for _, ctr := range containers.Workers { - events := make([]map[string]interface{}, 0, len(ctr.ContainerEvents)) + events := make([]map[string]any, 0, len(ctr.ContainerEvents)) for _, event := range ctr.ContainerEvents { - events = append(events, map[string]interface{}{ + events = append(events, map[string]any{ "time": event.Time.Unix(), "message": event.Message, }) } - items = append(items, map[string]interface{}{ + items = append(items, map[string]any{ "container_id": ctr.ContainerID, "device_id": ctr.DeviceID, "status": strings.ToLower(strings.TrimSpace(ctr.Status)), @@ -784,9 +781,9 @@ func GetContainerDetails(c *gin.Context) { return } - events := make([]map[string]interface{}, 0, len(details.ContainerEvents)) + events := make([]map[string]any, 0, len(details.ContainerEvents)) for _, event := range details.ContainerEvents { - events = append(events, map[string]interface{}{ + events = append(events, map[string]any{ "time": event.Time.Unix(), "message": event.Message, }) diff --git a/controller/email_binding.go b/controller/email_binding.go index a46724b013..61869c7d4f 100644 --- a/controller/email_binding.go +++ b/controller/email_binding.go @@ -25,7 +25,7 @@ func EmailBindStart(c *gin.Context) { } succeeded, notificationFailed := false, false defer func() { - recordUserSecurityAudit(c, identity.UserID, "user.binding_start", map[string]interface{}{"provider": "email", "success": succeeded, "notification_failed": notificationFailed}) + recordUserSecurityAudit(c, identity.UserID, "user.binding_start", map[string]any{"provider": "email", "success": succeeded, "notification_failed": notificationFailed}) }() var request emailBindRequest if err := common.DecodeJson(c.Request.Body, &request); err != nil { @@ -63,7 +63,7 @@ func EmailBindResend(c *gin.Context) { } succeeded := false defer func() { - recordUserSecurityAudit(c, identity.UserID, "user.email_binding_resend", map[string]interface{}{"success": succeeded}) + recordUserSecurityAudit(c, identity.UserID, "user.email_binding_resend", map[string]any{"success": succeeded}) }() var request emailBindRequest if err := common.DecodeJson(c.Request.Body, &request); err != nil || request.FlowToken == "" { @@ -87,7 +87,7 @@ func EmailBind(c *gin.Context) { } succeeded, notificationFailed := false, false defer func() { - recordUserSecurityAudit(c, identity.UserID, "user.binding_bind", map[string]interface{}{"provider": "email", "success": succeeded, "notification_failed": notificationFailed}) + recordUserSecurityAudit(c, identity.UserID, "user.binding_bind", map[string]any{"provider": "email", "success": succeeded, "notification_failed": notificationFailed}) }() var request emailBindRequest if err := common.DecodeJson(c.Request.Body, &request); err != nil || request.FlowToken == "" { diff --git a/controller/group.go b/controller/group.go index 6ba339a3f9..6d1abec42c 100644 --- a/controller/group.go +++ b/controller/group.go @@ -24,7 +24,7 @@ func GetGroups(c *gin.Context) { } func GetUserGroups(c *gin.Context) { - usableGroups := make(map[string]map[string]interface{}) + usableGroups := make(map[string]map[string]any) userGroup := "" userId := c.GetInt("id") userGroup, _ = model.GetUserGroup(userId, false) @@ -32,14 +32,14 @@ func GetUserGroups(c *gin.Context) { for groupName, _ := range ratio_setting.GetGroupRatioCopy() { // UserUsableGroups contains the groups that the user can use if desc, ok := userUsableGroups[groupName]; ok { - usableGroups[groupName] = map[string]interface{}{ + usableGroups[groupName] = map[string]any{ "ratio": service.GetUserGroupRatio(userGroup, groupName), "desc": desc, } } } if _, ok := userUsableGroups["auto"]; ok { - usableGroups["auto"] = map[string]interface{}{ + usableGroups["auto"] = map[string]any{ "ratio": "自动", "desc": setting.GetUsableGroupDescription("auto"), } diff --git a/controller/model.go b/controller/model.go index 54d71f2568..6f81801faf 100644 --- a/controller/model.go +++ b/controller/model.go @@ -34,7 +34,7 @@ var channelId2Models map[int][]string func init() { // https://platform.openai.com/docs/models/model-endpoint-compatibility - for i := 0; i < constant.APITypeDummy; i++ { + for i := range constant.APITypeDummy { if i == constant.APITypeAIProxyLibrary { continue } diff --git a/controller/model_management_test.go b/controller/model_management_test.go index 2fabfa805f..e973759147 100644 --- a/controller/model_management_test.go +++ b/controller/model_management_test.go @@ -512,13 +512,11 @@ export function parseTaskResult() { return {}; } update := model.MetadataSyncUpdate{MetadataSyncSelection: model.MetadataSyncSelection{ModelName: "matrix-concurrent-import", RecordVersion: model.MetadataRecordVersion(nil, nil, nil), Create: true}, Values: model.MetadataValues{Description: "Imported", Status: 1}} var wg sync.WaitGroup results := make(chan error, 2) - for i := 0; i < 2; i++ { - wg.Add(1) - go func() { - defer wg.Done() + for range 2 { + wg.Go(func() { _, err := model.ApplyMetadataSync([]model.MetadataSyncUpdate{update}, nil) results <- err - }() + }) } wg.Wait() close(results) diff --git a/controller/model_meta.go b/controller/model_meta.go index c0417afc58..593d79cca3 100644 --- a/controller/model_meta.go +++ b/controller/model_meta.go @@ -215,7 +215,7 @@ func DeleteModelMeta(c *gin.Context) { common.ApiError(c, err) return } - recordManageAudit(c, "model.delete", map[string]interface{}{"model_ids": []int{id}, "remove_from_channels": removeFromChannels, "remove_pricing": removePricing, "updated_channels": result.UpdatedChannels}) + recordManageAudit(c, "model.delete", map[string]any{"model_ids": []int{id}, "remove_from_channels": removeFromChannels, "remove_pricing": removePricing, "updated_channels": result.UpdatedChannels}) common.ApiSuccess(c, result) } @@ -238,7 +238,7 @@ func BatchDeleteModelMeta(c *gin.Context) { common.ApiError(c, err) return } - recordManageAudit(c, "model.delete_batch", map[string]interface{}{"model_ids": request.ModelIDs, "remove_from_channels": request.RemoveFromChannels, "remove_pricing": request.RemovePricing, "updated_channels": result.UpdatedChannels}) + recordManageAudit(c, "model.delete_batch", map[string]any{"model_ids": request.ModelIDs, "remove_from_channels": request.RemoveFromChannels, "remove_pricing": request.RemovePricing, "updated_channels": result.UpdatedChannels}) common.ApiSuccess(c, result) } diff --git a/controller/model_pricing_config.go b/controller/model_pricing_config.go index 9fb23c5301..7627fe9d34 100644 --- a/controller/model_pricing_config.go +++ b/controller/model_pricing_config.go @@ -38,6 +38,6 @@ func UpdateModelPricingConfig(c *gin.Context) { for _, change := range request.Changes { names = append(names, change.ModelName) } - recordManageAudit(c, "model.pricing.update", map[string]interface{}{"models": names}) + recordManageAudit(c, "model.pricing.update", map[string]any{"models": names}) common.ApiSuccess(c, gin.H{"updated_models": names}) } diff --git a/controller/model_sync.go b/controller/model_sync.go index 6cb6608d26..95f7ab72e8 100644 --- a/controller/model_sync.go +++ b/controller/model_sync.go @@ -126,10 +126,7 @@ func getHTTPClient() *http.Client { func fetchJSON[T any](ctx context.Context, url string, out *upstreamEnvelope[T]) error { var lastErr error - attempts := common.GetEnvOrDefault("SYNC_HTTP_RETRY", 3) - if attempts < 1 { - attempts = 1 - } + attempts := max(common.GetEnvOrDefault("SYNC_HTTP_RETRY", 3), 1) baseDelay := 200 * time.Millisecond maxMB := common.GetEnvOrDefault("SYNC_HTTP_MAX_MB", 10) maxBytes := int64(maxMB) << 20 @@ -450,6 +447,6 @@ func SyncUpstreamModels(c *gin.Context) { c.JSON(status, gin.H{"success": false, "message": err.Error()}) return } - recordManageAudit(c, "model.metadata.sync", map[string]interface{}{"created_models": result.CreatedModels, "updated_models": result.UpdatedModels, "created_vendors": result.CreatedVendors}) + recordManageAudit(c, "model.metadata.sync", map[string]any{"created_models": result.CreatedModels, "updated_models": result.UpdatedModels, "created_vendors": result.CreatedVendors}) common.ApiSuccess(c, result) } diff --git a/controller/oauth.go b/controller/oauth.go index cbcffa84af..d2e92e76da 100644 --- a/controller/oauth.go +++ b/controller/oauth.go @@ -82,7 +82,7 @@ func GenerateOAuthCode(c *gin.Context) { sessionID = identity.SessionID if request.Intent == model.AuthFlowIntentBind { defer func() { - recordUserSecurityAudit(c, userID, "user.binding_start", map[string]interface{}{"provider": request.Provider, "success": bindingStarted}) + recordUserSecurityAudit(c, userID, "user.binding_start", map[string]any{"provider": request.Provider, "success": bindingStarted}) }() context, err := common.Marshal(service.AccountBindingContext{Provider: request.Provider}) if err != nil { @@ -176,7 +176,7 @@ func HandleOAuth(c *gin.Context) { bindSucceeded, notificationFailed := false, false if pendingFlow.Intent == model.AuthFlowIntentBind { defer func() { - recordUserSecurityAudit(c, pendingFlow.UserId, "user.binding_bind", map[string]interface{}{"provider": providerName, "success": bindSucceeded, "notification_failed": notificationFailed}) + recordUserSecurityAudit(c, pendingFlow.UserId, "user.binding_bind", map[string]any{"provider": providerName, "success": bindSucceeded, "notification_failed": notificationFailed}) }() } // Bind and verification callbacks must use the dashboard session that started them. @@ -310,7 +310,7 @@ func handleOAuthVerification(c *gin.Context, provider string, oauthUser *oauth.O writeSecurityOperationError(c, err) return } - recordUserSecurityAudit(c, identity.UserID, "user.security_verify", map[string]interface{}{"method": proof.Method, "scope": proof.Scope, "provider": provider}) + recordUserSecurityAudit(c, identity.UserID, "user.security_verify", map[string]any{"method": proof.Method, "scope": proof.Scope, "provider": provider}) common.ApiSuccess(c, proof) } @@ -527,7 +527,7 @@ func findOrCreateOAuthUser(c *gin.Context, provider oauth.Provider, oauthUser *o // Set the provider user ID on the user model and update provider.SetProviderUserID(user, oauthUser.ProviderUserID) - if err := tx.Model(user).Updates(map[string]interface{}{ + if err := tx.Model(user).Updates(map[string]any{ "github_id": user.GitHubId, "discord_id": user.DiscordId, "oidc_id": user.OidcId, diff --git a/controller/option.go b/controller/option.go index fa6f731e17..1121b9b435 100644 --- a/controller/option.go +++ b/controller/option.go @@ -421,7 +421,7 @@ func UpdateOption(c *gin.Context) { return } // 出于安全考虑只记录被修改的配置项名称,不记录配置值(可能含密钥等敏感信息)。 - recordManageAudit(c, "option.update", map[string]interface{}{ + recordManageAudit(c, "option.update", map[string]any{ "key": option.Key, }) c.JSON(http.StatusOK, gin.H{ diff --git a/controller/passkey.go b/controller/passkey.go index e40f0e76f3..94fc10665a 100644 --- a/controller/passkey.go +++ b/controller/passkey.go @@ -463,7 +463,7 @@ func AdminResetPasskey(c *gin.Context) { return } - recordManageAuditFor(c, user.Id, "user.reset_passkey", map[string]interface{}{ + recordManageAuditFor(c, user.Id, "user.reset_passkey", map[string]any{ "username": user.Username, "id": user.Id, }) @@ -628,7 +628,7 @@ func PasskeyVerifyFinish(c *gin.Context) { return } - recordUserSecurityAudit(c, user.Id, "user.security_verify", map[string]interface{}{"method": proof.Method, "scope": proof.Scope}) + recordUserSecurityAudit(c, user.Id, "user.security_verify", map[string]any{"method": proof.Method, "scope": proof.Scope}) common.ApiSuccess(c, proof) } diff --git a/controller/pricing.go b/controller/pricing.go index 8252327244..ce3939c224 100644 --- a/controller/pricing.go +++ b/controller/pricing.go @@ -1,6 +1,8 @@ package controller import ( + "maps" + "github.com/QuantumNous/new-api/common" "github.com/QuantumNous/new-api/model" "github.com/QuantumNous/new-api/service" @@ -38,9 +40,7 @@ func GetPricing(c *gin.Context) { userId, exists := c.Get("id") usableGroup := map[string]string{} groupRatio := map[string]float64{} - for s, f := range ratio_setting.GetGroupRatioCopy() { - groupRatio[s] = f - } + maps.Copy(groupRatio, ratio_setting.GetGroupRatioCopy()) var group string if exists { user, err := model.GetUserCache(userId.(int)) diff --git a/controller/ratio_sync.go b/controller/ratio_sync.go index 1fb04290bb..a2cc6303a6 100644 --- a/controller/ratio_sync.go +++ b/controller/ratio_sync.go @@ -52,7 +52,7 @@ func nearlyEqual(a, b float64) bool { return b-a < floatEpsilon } -func valuesEqual(a, b interface{}) bool { +func valuesEqual(a, b any) bool { af, aok := a.(float64) bf, bok := b.(float64) if aok && bok { @@ -352,7 +352,7 @@ func FetchUpstreamRatios(c *gin.Context) { // 简单重试:最多 3 次,指数退避 var resp *http.Response var lastErr error - for attempt := 0; attempt < 3; attempt++ { + for attempt := range 3 { resp, lastErr = client.Do(httpReq) if lastErr == nil { break @@ -709,12 +709,12 @@ func buildDifferences(localData map[string]any, successfulChannels []struct { if expressionPriority && numericPricingSyncFields[ratioType] { continue } - var localValue interface{} = nil + var localValue any = nil if val, exists := valueMap(localData[ratioType])[modelName]; exists { localValue = normalizeSyncValue(ratioType, val) } - upstreamValues := make(map[string]interface{}) + upstreamValues := make(map[string]any) confidenceValues := make(map[string]bool) hasUpstreamValue := false hasDifference := false @@ -723,7 +723,7 @@ func buildDifferences(localData map[string]any, successfulChannels []struct { if expressionPriority && valueMap(channel.data[billing_setting.BillingModeField])[modelName] != billing_setting.BillingModeTieredExpr { continue } - var upstreamValue interface{} = nil + var upstreamValue any = nil if val, exists := valueMap(channel.data[ratioType])[modelName]; exists { upstreamValue = normalizeSyncValue(ratioType, val) diff --git a/controller/redemption.go b/controller/redemption.go index a6637610e7..a3c8dcef10 100644 --- a/controller/redemption.go +++ b/controller/redemption.go @@ -121,7 +121,7 @@ func AddRedemption(c *gin.Context) { } keys = append(keys, key) } - recordManageAudit(c, "redemption.create", map[string]interface{}{ + recordManageAudit(c, "redemption.create", map[string]any{ "name": redemption.Name, "count": redemption.Count, "quota": logger.LogQuota(redemption.Quota), diff --git a/controller/relay_error_log_test.go b/controller/relay_error_log_test.go index 737c058059..b214a7d4ce 100644 --- a/controller/relay_error_log_test.go +++ b/controller/relay_error_log_test.go @@ -80,9 +80,9 @@ func TestProcessChannelErrorUsesSnapshotWithoutLeakingChannelMetadata(t *testing for _, key := range []string{"channel_id", "channel_name", "channel_type"} { assert.NotContains(t, storedOther, key) } - adminInfo, ok := storedOther["admin_info"].(map[string]interface{}) + adminInfo, ok := storedOther["admin_info"].(map[string]any) require.True(t, ok) - assert.Equal(t, []interface{}{"101"}, adminInfo["use_channel"]) + assert.Equal(t, []any{"101"}, adminInfo["use_channel"]) logs, total, err := model.GetUserLogs(7, model.LogTypeError, 0, 0, "", "", 0, 10, "", "", "") require.NoError(t, err) diff --git a/controller/secure_verification.go b/controller/secure_verification.go index 71f31a6092..06dbd6b88c 100644 --- a/controller/secure_verification.go +++ b/controller/secure_verification.go @@ -131,6 +131,6 @@ func UniversalVerify(c *gin.Context) { writeSecurityOperationError(c, err) return } - recordUserSecurityAudit(c, identity.UserID, "user.security_verify", map[string]interface{}{"method": proof.Method, "scope": proof.Scope}) + recordUserSecurityAudit(c, identity.UserID, "user.security_verify", map[string]any{"method": proof.Method, "scope": proof.Scope}) common.ApiSuccess(c, proof) } diff --git a/controller/security_account_test.go b/controller/security_account_test.go index 321ed520ef..e76ab4c6b3 100644 --- a/controller/security_account_test.go +++ b/controller/security_account_test.go @@ -411,7 +411,7 @@ func TestSecurityAccountProfileReadsPasswordStatusInOneQuery(t *testing.T) { } t.Run(name, func(t *testing.T) { user, identity := setupSecurityEnrollmentTest(t) - updates := map[string]interface{}{"access_token": "private-profile-token", "remark": "private-profile-remark"} + updates := map[string]any{"access_token": "private-profile-token", "remark": "private-profile-remark"} if !hasPassword { updates["password"] = "" } @@ -433,8 +433,8 @@ func TestSecurityAccountProfileReadsPasswordStatusInOneQuery(t *testing.T) { response := securityEnrollmentRequest(http.MethodGet, "/api/user/self", "", "", identity, GetSelf) var result struct { - Success bool `json:"success"` - Data map[string]interface{} `json:"data"` + Success bool `json:"success"` + Data map[string]any `json:"data"` } require.NoError(t, common.Unmarshal(response.Body.Bytes(), &result)) require.True(t, result.Success, response.Body.String()) @@ -825,7 +825,7 @@ func TestSecurityAccountUnbindPreservesUsableLoginMethod(t *testing.T) { common.PasswordLoginEnabled = scenario != "disabled password" require.NoError(t, model.DB.Create(&model.UserOAuthBinding{UserId: user.Id, ProviderId: 31, ProviderUserId: "linked-subject"}).Error) if scenario != "password" && scenario != "disabled password" { - require.NoError(t, model.DB.Model(user).Updates(map[string]interface{}{"password": "", "email": "verified@example.com"}).Error) + require.NoError(t, model.DB.Model(user).Updates(map[string]any{"password": "", "email": "verified@example.com"}).Error) } if scenario == "passkey" || scenario == "disabled passkey" { require.NoError(t, model.DB.Create(&model.PasskeyCredential{UserID: user.Id, CredentialID: "existing-key", PublicKey: "public-key"}).Error) diff --git a/controller/security_enrollment_test.go b/controller/security_enrollment_test.go index 8437834a10..1df088c0db 100644 --- a/controller/security_enrollment_test.go +++ b/controller/security_enrollment_test.go @@ -1059,7 +1059,7 @@ func TestSecurityEnrollmentOAuthVerificationNeverChangesLoginOrBindings(t *testi for _, scenario := range []string{"success", "different account", "binding changed", "session changed", "auth version changed", "provider disabled", "cancelled"} { t.Run(scenario, func(t *testing.T) { user, identity := setupSecurityEnrollmentTest(t) - require.NoError(t, model.DB.Model(user).Updates(map[string]interface{}{"password": "", "github_id": "linked-user", "email": "same@example.com"}).Error) + require.NoError(t, model.DB.Model(user).Updates(map[string]any{"password": "", "github_id": "linked-user", "email": "same@example.com"}).Error) provider := &enrollmentOAuthProvider{externalID: "linked-user"} oauth.Register("enrollment-oauth", provider) t.Cleanup(func() { oauth.Unregister("enrollment-oauth") }) diff --git a/controller/subscription.go b/controller/subscription.go index 946a1e0ba6..599b82dcd9 100644 --- a/controller/subscription.go +++ b/controller/subscription.go @@ -281,7 +281,7 @@ func AdminUpdateSubscriptionPlan(c *gin.Context) { err := model.DB.Transaction(func(tx *gorm.DB) error { // update plan (allow zero values updates with map) - updateMap := map[string]interface{}{ + updateMap := map[string]any{ "title": req.Plan.Title, "subtitle": req.Plan.Subtitle, "price_amount": req.Plan.PriceAmount, @@ -467,7 +467,7 @@ func AdminResetUserSubscriptionsByPlan(c *gin.Context) { return } recordSubscriptionResetUserLogs(c, result, auditOperatorInfo(c)) - recordManageAuditFor(c, userId, "subscription.user_plan_reset", map[string]interface{}{ + recordManageAuditFor(c, userId, "subscription.user_plan_reset", map[string]any{ "target_user_id": userId, "plan_id": result.PlanId, "plan_title": result.PlanTitle, @@ -498,7 +498,7 @@ func AdminResetPlanSubscriptions(c *gin.Context) { recordSubscriptionResetUserLogs(c, result, auditOperatorInfo(c)) common.SysLog(fmt.Sprintf("admin reset subscription plan %d quota: reset_count=%d user_count=%d advance_reset_time=%t", result.PlanId, result.ResetCount, result.UserCount, result.AdvanceResetTime)) - recordManageAudit(c, "subscription.plan_reset", map[string]interface{}{ + recordManageAudit(c, "subscription.plan_reset", map[string]any{ "plan_id": result.PlanId, "plan_title": result.PlanTitle, "reset_count": result.ResetCount, diff --git a/controller/task_plugin.go b/controller/task_plugin.go index 50eb2511d0..212f1b43f9 100644 --- a/controller/task_plugin.go +++ b/controller/task_plugin.go @@ -6,6 +6,7 @@ import ( "encoding/json" "errors" "fmt" + "maps" "net/http" "net/url" "sort" @@ -167,9 +168,7 @@ func ListTaskPlugins(c *gin.Context) { runtimeErrors := jsplugin.DefaultRegistry.RoutingErrors() taskPluginSyncState.Lock() - for key, message := range taskPluginSyncState.errors { - runtimeErrors[key] = message - } + maps.Copy(runtimeErrors, taskPluginSyncState.errors) taskPluginSyncState.Unlock() items := make([]taskPluginListItem, 0, len(keys)) @@ -249,9 +248,7 @@ func GetTaskPluginRuntime(c *gin.Context) { pluginErrors := routingStatus.Errors taskPluginSyncState.Lock() - for key, message := range taskPluginSyncState.errors { - pluginErrors[key] = message - } + maps.Copy(pluginErrors, taskPluginSyncState.errors) lastRebuild := taskPluginSyncState.lastRebuild lastDatabaseRevision := lastRebuild.DatabaseRevision taskPluginSyncState.Unlock() @@ -797,9 +794,7 @@ func syncTaskPluginsOnceContext(ctx context.Context) error { } } pluginErrors := jsplugin.DefaultRegistry.RoutingErrors() - for key, message := range taskPluginSyncState.errors { - pluginErrors[key] = message - } + maps.Copy(pluginErrors, taskPluginSyncState.errors) pluginErrorCount := len(pluginErrors) status := "success" if pluginErrorCount > 0 { diff --git a/controller/telegram_test.go b/controller/telegram_test.go index 6b7a23abaf..84686404f0 100644 --- a/controller/telegram_test.go +++ b/controller/telegram_test.go @@ -7,6 +7,7 @@ import ( "encoding/json" "errors" "fmt" + "maps" "math/big" "net/http" "net/http/httptest" @@ -67,9 +68,7 @@ func setupTelegramOAuthTest(t *testing.T) *telegramOAuthFixture { common.OptionMapRWMutex.Lock() previousOptions := common.OptionMap common.OptionMap = make(map[string]string) - for key, value := range previousOptions { - common.OptionMap[key] = value - } + maps.Copy(common.OptionMap, previousOptions) common.OptionMapRWMutex.Unlock() common.TelegramOAuthEnabled = true *system_setting.GetTelegramSettings() = system_setting.TelegramSettings{ClientID: "12345", ClientSecret: "telegram-client-secret"} diff --git a/controller/topup.go b/controller/topup.go index 30f8d22157..26c7b94c89 100644 --- a/controller/topup.go +++ b/controller/topup.go @@ -105,7 +105,7 @@ func GetTopUpInfo(c *gin.Context) { "enable_redemption": complianceConfirmed, "payment_compliance_confirmed": complianceConfirmed, "payment_compliance_terms_version": operation_setting.CurrentComplianceTermsVersion, - "waffo_pay_methods": func() interface{} { + "waffo_pay_methods": func() any { if enableWaffo { return setting.GetWaffoPayMethods() } diff --git a/controller/topup_waffo.go b/controller/topup_waffo.go index d803c881ff..869adce74a 100644 --- a/controller/topup_waffo.go +++ b/controller/topup_waffo.go @@ -217,10 +217,7 @@ func RequestWaffoPay(c *gin.Context) { // Token 模式下归一化 Amount(存等价美元/CNY 数量,避免 RechargeWaffo 双重放大) amount := req.Amount if operation_setting.GetQuotaDisplayType() == operation_setting.QuotaDisplayTypeTokens { - amount = int64(float64(req.Amount) / common.QuotaPerUnit) - if amount < 1 { - amount = 1 - } + amount = max(int64(float64(req.Amount)/common.QuotaPerUnit), 1) } // 创建本地订单 diff --git a/controller/topup_waffo_pancake_test.go b/controller/topup_waffo_pancake_test.go index 483dd7b793..1e0b6eb973 100644 --- a/controller/topup_waffo_pancake_test.go +++ b/controller/topup_waffo_pancake_test.go @@ -1,6 +1,7 @@ package controller import ( + "maps" "testing" "github.com/QuantumNous/new-api/common" @@ -31,9 +32,7 @@ func TestGetWaffoPancakePayMoney(t *testing.T) { originalUnitPrice := setting.WaffoPancakeUnitPrice originalQuotaDisplayType := operation_setting.GetGeneralSetting().QuotaDisplayType originalDiscounts := make(map[int]float64, len(operation_setting.GetPaymentSetting().AmountDiscount)) - for k, v := range operation_setting.GetPaymentSetting().AmountDiscount { - originalDiscounts[k] = v - } + maps.Copy(originalDiscounts, operation_setting.GetPaymentSetting().AmountDiscount) originalTopupGroupRatio := common.TopupGroupRatio2JSONString() t.Cleanup(func() { diff --git a/controller/twofa.go b/controller/twofa.go index d470040527..a8f3f5b636 100644 --- a/controller/twofa.go +++ b/controller/twofa.go @@ -96,7 +96,7 @@ func Get2FAStatus(c *gin.Context) { return } - status := map[string]interface{}{ + status := map[string]any{ "enabled": false, "locked": false, } diff --git a/controller/uptime_kuma.go b/controller/uptime_kuma.go index 2beceb426f..fce72dd7ca 100644 --- a/controller/uptime_kuma.go +++ b/controller/uptime_kuma.go @@ -35,7 +35,7 @@ type UptimeGroupResult struct { Monitors []Monitor `json:"monitors"` } -func getAndDecode(ctx context.Context, client *http.Client, url string, dest interface{}) error { +func getAndDecode(ctx context.Context, client *http.Client, url string, dest any) error { req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) if err != nil { return err @@ -54,7 +54,7 @@ func getAndDecode(ctx context.Context, client *http.Client, url string, dest int return json.NewDecoder(resp.Body).Decode(dest) } -func fetchGroupData(ctx context.Context, client *http.Client, groupConfig map[string]interface{}) UptimeGroupResult { +func fetchGroupData(ctx context.Context, client *http.Client, groupConfig map[string]any) UptimeGroupResult { url, _ := groupConfig["url"].(string) slug, _ := groupConfig["slug"].(string) categoryName, _ := groupConfig["categoryName"].(string) @@ -143,7 +143,6 @@ func GetUptimeKumaStatus(c *gin.Context) { g, gCtx := errgroup.WithContext(ctx) for i, group := range groups { - i, group := i, group g.Go(func() error { results[i] = fetchGroupData(gCtx, client, group) return nil diff --git a/controller/user.go b/controller/user.go index 946188d6ca..434767c884 100644 --- a/controller/user.go +++ b/controller/user.go @@ -134,7 +134,7 @@ func recordLoginAudit(user *model.User, c *gin.Context) { UserAgent: c.Request.UserAgent(), } content := fmt.Sprintf("Logged in successfully via %s", method) - params := map[string]interface{}{ + params := map[string]any{ "method": method, } if verifiedMethod := c.GetString("login_verification_method"); verifiedMethod != "" { @@ -486,11 +486,11 @@ func GetSelf(c *gin.Context) { // buildSelfUserData is the single safe dashboard-user DTO used by GetSelf, // login and refresh. It intentionally excludes password, management PAT and // administrator-only remarks. -func buildSelfUserData(user *model.User) map[string]interface{} { +func buildSelfUserData(user *model.User) map[string]any { userSetting := user.GetSetting() permissions := calculateUserPermissions(user.Role) permissions["admin_permissions"] = authz.Capabilities(user.Id, user.Role) - return map[string]interface{}{ + return map[string]any{ "id": user.Id, "username": user.Username, "display_name": user.DisplayName, @@ -521,26 +521,26 @@ func buildSelfUserData(user *model.User) map[string]interface{} { } // 计算用户权限的辅助函数 -func calculateUserPermissions(userRole int) map[string]interface{} { - permissions := map[string]interface{}{} +func calculateUserPermissions(userRole int) map[string]any { + permissions := map[string]any{} // 根据用户角色计算权限 if userRole == common.RoleRootUser { // 超级管理员不需要边栏设置功能 permissions["sidebar_settings"] = false - permissions["sidebar_modules"] = map[string]interface{}{} + permissions["sidebar_modules"] = map[string]any{} } else if userRole == common.RoleAdminUser { // 管理员可以设置边栏,但不包含系统设置功能 permissions["sidebar_settings"] = true - permissions["sidebar_modules"] = map[string]interface{}{ - "admin": map[string]interface{}{ + permissions["sidebar_modules"] = map[string]any{ + "admin": map[string]any{ "setting": false, // 管理员不能访问系统设置 }, } } else { // 普通用户只能设置个人功能,不包含管理员区域 permissions["sidebar_settings"] = true - permissions["sidebar_modules"] = map[string]interface{}{ + permissions["sidebar_modules"] = map[string]any{ "admin": false, // 普通用户不能访问管理员区域 } } @@ -550,17 +550,17 @@ func calculateUserPermissions(userRole int) map[string]interface{} { // 根据用户角色生成默认的边栏配置 func generateDefaultSidebarConfig(userRole int) string { - defaultConfig := map[string]interface{}{} + defaultConfig := map[string]any{} // 聊天区域 - 所有用户都可以访问 - defaultConfig["chat"] = map[string]interface{}{ + defaultConfig["chat"] = map[string]any{ "enabled": true, "playground": true, "chat": true, } // 控制台区域 - 所有用户都可以访问 - defaultConfig["console"] = map[string]interface{}{ + defaultConfig["console"] = map[string]any{ "enabled": true, "detail": true, "token": true, @@ -570,7 +570,7 @@ func generateDefaultSidebarConfig(userRole int) string { } // 个人中心区域 - 所有用户都可以访问 - defaultConfig["personal"] = map[string]interface{}{ + defaultConfig["personal"] = map[string]any{ "enabled": true, "topup": true, "personal": true, @@ -579,7 +579,7 @@ func generateDefaultSidebarConfig(userRole int) string { // 管理员区域 - 根据角色决定 if userRole == common.RoleAdminUser { // 管理员可以访问管理员区域,但不能访问系统设置 - defaultConfig["admin"] = map[string]interface{}{ + defaultConfig["admin"] = map[string]any{ "enabled": true, "channel": true, "models": true, @@ -589,7 +589,7 @@ func generateDefaultSidebarConfig(userRole int) string { } } else if userRole == common.RoleRootUser { // 超级管理员可以访问所有功能 - defaultConfig["admin"] = map[string]interface{}{ + defaultConfig["admin"] = map[string]any{ "enabled": true, "channel": true, "models": true, @@ -704,7 +704,7 @@ func UpdateUser(c *gin.Context) { common.ApiError(c, err) return } - recordManageAuditFor(c, updatedUser.Id, "user.update", map[string]interface{}{ + recordManageAuditFor(c, updatedUser.Id, "user.update", map[string]any{ "username": originUser.Username, "id": updatedUser.Id, }) @@ -745,7 +745,7 @@ func AdminClearUserBinding(c *gin.Context) { return } - recordManageAuditFor(c, user.Id, "user.binding_clear", map[string]interface{}{ + recordManageAuditFor(c, user.Id, "user.binding_clear", map[string]any{ "bindingType": bindingType, "username": user.Username, }) @@ -757,7 +757,7 @@ func AdminClearUserBinding(c *gin.Context) { } func UpdateSelf(c *gin.Context) { - var requestData map[string]interface{} + var requestData map[string]any if err := common.DecodeJson(c.Request.Body, &requestData); err != nil { common.ApiErrorI18n(c, i18n.MsgInvalidParams) return @@ -771,7 +771,7 @@ func UpdateSelf(c *gin.Context) { succeeded, notificationFailed := false, false if passwordRequested { defer func() { - recordUserSecurityAudit(c, c.GetInt("id"), "user.password_change", map[string]interface{}{"success": succeeded, "notification_failed": notificationFailed}) + recordUserSecurityAudit(c, c.GetInt("id"), "user.password_change", map[string]any{"success": succeeded, "notification_failed": notificationFailed}) }() } // 检查是否是用户设置更新请求 (sidebar_modules 或 language) @@ -928,7 +928,7 @@ func DeleteUser(c *gin.Context) { common.ApiError(c, err) return } - recordManageAuditFor(c, originUser.Id, "user.delete", map[string]interface{}{ + recordManageAuditFor(c, originUser.Id, "user.delete", map[string]any{ "username": originUser.Username, "id": originUser.Id, }) @@ -943,7 +943,7 @@ func DeleteSelf(c *gin.Context) { setAuthNoStore(c) succeeded := false defer func() { - recordUserSecurityAudit(c, c.GetInt("id"), "user.account_delete", map[string]interface{}{"success": succeeded}) + recordUserSecurityAudit(c, c.GetInt("id"), "user.account_delete", map[string]any{"success": succeeded}) }() if middleware.RequireSecurityProof(c, service.VerificationOperation{Scope: service.VerificationScopeAccountDelete}) == nil { return @@ -1013,7 +1013,7 @@ func CreateUser(c *gin.Context) { } cleanUser.FinishInsert(0) - recordManageAuditFor(c, cleanUser.Id, "user.create", map[string]interface{}{ + recordManageAuditFor(c, cleanUser.Id, "user.create", map[string]any{ "username": cleanUser.Username, "role": cleanUser.Role, }) @@ -1100,7 +1100,7 @@ func ManageUser(c *gin.Context) { if err := model.InvalidateUserTokensCache(user.Id); err != nil { common.SysLog(fmt.Sprintf("failed to invalidate tokens cache for user %d: %s", user.Id, err.Error())) } - recordManageAuditFor(c, user.Id, "user.manage", map[string]interface{}{ + recordManageAuditFor(c, user.Id, "user.manage", map[string]any{ "action": req.Action, "username": user.Username, "id": user.Id, @@ -1170,7 +1170,7 @@ func ManageUser(c *gin.Context) { if err := model.InvalidateUserTokensCache(user.Id); err != nil { common.SysLog(fmt.Sprintf("failed to invalidate tokens cache for user %d: %s", user.Id, err.Error())) } - recordManageAuditFor(c, user.Id, "user.manage", map[string]interface{}{ + recordManageAuditFor(c, user.Id, "user.manage", map[string]any{ "action": req.Action, "username": user.Username, "id": user.Id, diff --git a/controller/wechat.go b/controller/wechat.go index 43755b2899..6655960164 100644 --- a/controller/wechat.go +++ b/controller/wechat.go @@ -136,7 +136,7 @@ func WeChatBind(c *gin.Context) { } succeeded, notificationFailed := false, false defer func() { - recordUserSecurityAudit(c, identity.UserID, "user.binding_bind", map[string]interface{}{"provider": "wechat", "success": succeeded, "notification_failed": notificationFailed}) + recordUserSecurityAudit(c, identity.UserID, "user.binding_bind", map[string]any{"provider": "wechat", "success": succeeded, "notification_failed": notificationFailed}) }() if !common.WeChatAuthEnabled { c.JSON(http.StatusOK, gin.H{ diff --git a/dto/midjourney.go b/dto/midjourney.go index 6fbcb3574f..5df9908444 100644 --- a/dto/midjourney.go +++ b/dto/midjourney.go @@ -27,10 +27,10 @@ type MidjourneyRequest struct { } type MidjourneyResponse struct { - Code int `json:"code"` - Description string `json:"description"` - Properties interface{} `json:"properties"` - Result string `json:"result"` + Code int `json:"code"` + Description string `json:"description"` + Properties any `json:"properties"` + Result string `json:"result"` } type MidjourneyUploadResponse struct { diff --git a/dto/suno.go b/dto/suno.go index 90e11b8109..aa2d8f78f0 100644 --- a/dto/suno.go +++ b/dto/suno.go @@ -42,13 +42,13 @@ type SunoSong struct { } type SunoMetadata struct { - Tags string `json:"tags"` - Prompt string `json:"prompt"` - GPTDescriptionPrompt interface{} `json:"gpt_description_prompt"` - AudioPromptID interface{} `json:"audio_prompt_id"` - Duration interface{} `json:"duration"` - ErrorType interface{} `json:"error_type"` - ErrorMessage interface{} `json:"error_message"` + Tags string `json:"tags"` + Prompt string `json:"prompt"` + GPTDescriptionPrompt any `json:"gpt_description_prompt"` + AudioPromptID any `json:"audio_prompt_id"` + Duration any `json:"duration"` + ErrorType any `json:"error_type"` + ErrorMessage any `json:"error_message"` } type SunoLyrics struct { diff --git a/middleware/audit.go b/middleware/audit.go index 626e472c9e..cc4258c87d 100644 --- a/middleware/audit.go +++ b/middleware/audit.go @@ -151,7 +151,7 @@ func finishAdminAudit(c *gin.Context, writer *auditResponseWriter) { } // op.params 为语言无关参数,供前端 i18n 渲染;generic 时携带 method/route。 - opParams := map[string]interface{}{} + opParams := map[string]any{} if action == "generic" { opParams["method"] = method opParams["route"] = route diff --git a/middleware/auth.go b/middleware/auth.go index 5ad83f8918..63775a5d23 100644 --- a/middleware/auth.go +++ b/middleware/auth.go @@ -365,8 +365,8 @@ func TokenAuth() func(c *gin.Context) { // Sec-WebSocket-Protocol: realtime, openai-insecure-api-key.sk-xxx, openai-beta.realtime-v1 // read sk from Sec-WebSocket-Protocol key := c.Request.Header.Get("Sec-WebSocket-Protocol") - parts := strings.Split(key, ",") - for _, part := range parts { + parts := strings.SplitSeq(key, ",") + for part := range parts { part = strings.TrimSpace(part) if strings.HasPrefix(part, "openai-insecure-api-key") { key = strings.TrimPrefix(part, "openai-insecure-api-key.") diff --git a/middleware/rate-limit.go b/middleware/rate-limit.go index be1820ffee..4324174fdf 100644 --- a/middleware/rate-limit.go +++ b/middleware/rate-limit.go @@ -49,7 +49,7 @@ func redisUserRateLimitKey(mark string, userID int) string { return fmt.Sprintf("%s:user:%s:%d", redisRateLimitNamespace, mark, userID) } -func redisReplyInteger(value interface{}) (int64, error) { +func redisReplyInteger(value any) (int64, error) { switch typed := value.(type) { case int64: return typed, nil diff --git a/middleware/task_artifact_access.go b/middleware/task_artifact_access.go index 49a827a56a..3ef1468656 100644 --- a/middleware/task_artifact_access.go +++ b/middleware/task_artifact_access.go @@ -139,7 +139,7 @@ func popTaskArtifactAccessQuery(request *http.Request) (string, bool, bool) { count := 0 invalid := false kept := make([]string, 0) - for _, part := range strings.Split(request.URL.RawQuery, "&") { + for part := range strings.SplitSeq(request.URL.RawQuery, "&") { rawKey, rawValue, _ := strings.Cut(part, "=") key, err := url.QueryUnescape(rawKey) if err != nil || key != service.TaskArtifactAccessQueryParameter { diff --git a/model/audit_log.go b/model/audit_log.go index 4192bf7c59..2fa65877f8 100644 --- a/model/audit_log.go +++ b/model/audit_log.go @@ -116,7 +116,7 @@ func RecordAuditLog(c *gin.Context, entry AuditLog) { logger.LogError(ctx, fmt.Sprintf("audit log write failed (request_id=%s): log database unavailable", entry.RequestId)) return } - var row interface{} = &entry + var row any = &entry if common.UsingLogDatabase(common.DatabaseTypeClickHouse) { encoded, err := common.Marshal(entry.Other) if err != nil { diff --git a/model/channel.go b/model/channel.go index 268f190e70..f62ed09e84 100644 --- a/model/channel.go +++ b/model/channel.go @@ -173,7 +173,7 @@ func (c ChannelInfo) Value() (driver.Value, error) { } // Scan implements sql.Scanner interface -func (c *ChannelInfo) Scan(value interface{}) error { +func (c *ChannelInfo) Scan(value any) error { return common.Unmarshal(jsonScanBytes(value), c) } @@ -271,7 +271,7 @@ func (channel *Channel) GetNextEnabledKey() (string, int, *types.NewAPIError) { if start < 0 || start >= len(keys) { start = 0 } - for i := 0; i < len(keys); i++ { + for i := range keys { idx := (start + i) % len(keys) if getStatus(idx) == common.ChannelStatusEnabled { // update polling index for next call (point to the next position) @@ -309,8 +309,8 @@ func (channel *Channel) GetGroups() []string { return groups } -func (channel *Channel) GetOtherInfo() map[string]interface{} { - otherInfo := make(map[string]interface{}) +func (channel *Channel) GetOtherInfo() map[string]any { + otherInfo := make(map[string]any) if channel.OtherInfo != "" { err := common.Unmarshal([]byte(channel.OtherInfo), &otherInfo) if err != nil { @@ -320,7 +320,7 @@ func (channel *Channel) GetOtherInfo() map[string]interface{} { return otherInfo } -func (channel *Channel) SetOtherInfo(otherInfo map[string]interface{}) { +func (channel *Channel) SetOtherInfo(otherInfo map[string]any) { otherInfoBytes, err := json.Marshal(otherInfo) if err != nil { common.SysLog(fmt.Sprintf("failed to marshal other info: channel_id=%d, tag=%s, name=%s, error=%v", channel.Id, channel.GetTag(), channel.Name, err)) @@ -659,7 +659,7 @@ func CleanupChannelPollingLocks() { activeChannelSet[id] = true } - channelPollingLocks.Range(func(key, value interface{}) bool { + channelPollingLocks.Range(func(key, value any) bool { channelId := key.(int) if !activeChannelSet[channelId] { channelPollingLocks.Delete(channelId) @@ -1054,8 +1054,8 @@ func (channel *Channel) SetOtherSettings(setting dto.ChannelOtherSettings) { channel.OtherSettings = string(settingBytes) } -func (channel *Channel) GetParamOverride() map[string]interface{} { - paramOverride := make(map[string]interface{}) +func (channel *Channel) GetParamOverride() map[string]any { + paramOverride := make(map[string]any) if channel.ParamOverride != nil && *channel.ParamOverride != "" { err := common.Unmarshal([]byte(*channel.ParamOverride), ¶mOverride) if err != nil { @@ -1065,8 +1065,8 @@ func (channel *Channel) GetParamOverride() map[string]interface{} { return paramOverride } -func (channel *Channel) GetHeaderOverride() map[string]interface{} { - headerOverride := make(map[string]interface{}) +func (channel *Channel) GetHeaderOverride() map[string]any { + headerOverride := make(map[string]any) if channel.HeaderOverride != nil && *channel.HeaderOverride != "" { err := common.Unmarshal([]byte(*channel.HeaderOverride), &headerOverride) if err != nil { diff --git a/model/channel_cache.go b/model/channel_cache.go index 1fcfe61bce..fa1107effe 100644 --- a/model/channel_cache.go +++ b/model/channel_cache.go @@ -56,8 +56,8 @@ func InitChannelCache() { if channel.Status != common.ChannelStatusEnabled { continue // skip disabled channels } - groups := strings.Split(channel.Group, ",") - for _, group := range groups { + groups := strings.SplitSeq(channel.Group, ",") + for group := range groups { models := channel.GetModels() for _, model := range models { if _, ok := newGroup2model2channels[group][model]; !ok { diff --git a/model/channel_satisfy.go b/model/channel_satisfy.go index f91be89296..32cbc244f6 100644 --- a/model/channel_satisfy.go +++ b/model/channel_satisfy.go @@ -1,6 +1,8 @@ package model import ( + "slices" + "github.com/QuantumNous/new-api/common" "github.com/QuantumNous/new-api/setting/ratio_setting" ) @@ -62,10 +64,5 @@ func isChannelEnabledForGroupModelDB(group string, modelName string, channelID i } func isChannelIDInList(list []int, channelID int) bool { - for _, id := range list { - if id == channelID { - return true - } - } - return false + return slices.Contains(list, channelID) } diff --git a/model/channel_status_test.go b/model/channel_status_test.go index e4ad86f813..57e44f7733 100644 --- a/model/channel_status_test.go +++ b/model/channel_status_test.go @@ -82,7 +82,7 @@ func TestSaveStatusStateFromSingleKeySnapshotPreservesUnownedColumns(t *testing. }).Error) stale.Status = common.ChannelStatusManuallyDisabled - stale.SetOtherInfo(map[string]interface{}{ + stale.SetOtherInfo(map[string]any{ "status_reason": "manual operation", "status_time": int64(1234), }) diff --git a/model/checkin.go b/model/checkin.go index 93c94909dd..e72d132c13 100644 --- a/model/checkin.go +++ b/model/checkin.go @@ -141,7 +141,7 @@ func userCheckinWithoutTransaction(checkin *Checkin, userId int, quotaAwarded in } // GetUserCheckinStats 获取用户签到统计信息 -func GetUserCheckinStats(userId int, month string) (map[string]interface{}, error) { +func GetUserCheckinStats(userId int, month string) (map[string]any, error) { // 获取指定月份的所有签到记录 startDate := month + "-01" endDate := month + "-31" @@ -169,7 +169,7 @@ func GetUserCheckinStats(userId int, month string) (map[string]interface{}, erro DB.Model(&Checkin{}).Where("user_id = ?", userId).Count(&totalCheckins) DB.Model(&Checkin{}).Where("user_id = ?", userId).Select("COALESCE(SUM(quota_awarded), 0)").Scan(&totalQuota) - return map[string]interface{}{ + return map[string]any{ "total_quota": totalQuota, // 所有时间累计获得的额度 "total_checkins": totalCheckins, // 所有时间累计签到次数 "checkin_count": len(records), // 本月签到次数 diff --git a/model/gorm_logger.go b/model/gorm_logger.go index e48f057b73..f2cd989032 100644 --- a/model/gorm_logger.go +++ b/model/gorm_logger.go @@ -52,7 +52,7 @@ type sanitizedLogWriter struct { delegate *log.Logger } -func (s *sanitizedLogWriter) Printf(format string, args ...interface{}) { +func (s *sanitizedLogWriter) Printf(format string, args ...any) { if !common.DebugEnabled { for i, arg := range args { if err, ok := arg.(error); ok { diff --git a/model/json_column_test.go b/model/json_column_test.go index 59272629d0..cb84d3b406 100644 --- a/model/json_column_test.go +++ b/model/json_column_test.go @@ -68,7 +68,7 @@ func TestJSONColumnValuersZeroValueIsNil(t *testing.T) { // 保护契约:json 列的 Scan 必须同时接受 []byte 与 string——不同驱动/协议 // 模式返回类型不同,静默丢弃 string 会把已有数据清零。 func TestJSONColumnScannersAcceptStringAndBytes(t *testing.T) { - toInput := func(kind string, payload string) interface{} { + toInput := func(kind string, payload string) any { if kind == "bytes" { return []byte(payload) } diff --git a/model/log.go b/model/log.go index 9623fa637e..a56d26e428 100644 --- a/model/log.go +++ b/model/log.go @@ -211,7 +211,7 @@ func RecordLogWithAdminInfo(userId int, logType int, content string, adminInfo * // username 由调用方传入(登录流程已持有用户对象),避免额外的数据库查询。 // content 为英文兜底文本(用于导出);action+params 供前端本地化渲染。 // other 包含 login_method、user_agent 等结构化信息。 -func RecordLoginLog(userId, actorRole int, username string, content string, ip string, action string, params map[string]interface{}, other AuditOther, request ...*gin.Context) { +func RecordLoginLog(userId, actorRole int, username string, content string, ip string, action string, params map[string]any, other AuditOther, request ...*gin.Context) { other.Op = &AuditOperation{Action: action, Params: params} var c *gin.Context if len(request) > 0 { @@ -226,7 +226,7 @@ func RecordLoginLog(userId, actorRole int, username string, content string, ip s // action+params 写入 Other.op,供前端本地化渲染(普通用户可见,不含敏感信息)。 // adminInfo 存放操作者身份(写入 Other.admin_info,普通用户查询时剥离); // auditInfo 存放路由/方法/结果等中间件兜底信息(写入 Other.audit_info,普通用户查询时剥离)。 -func RecordOperationAuditLog(logUserId, actorRole int, content string, ip string, action string, params map[string]interface{}, adminInfo *AuditAdminInfo, auditInfo *AuditRequestInfo, request ...*gin.Context) { +func RecordOperationAuditLog(logUserId, actorRole int, content string, ip string, action string, params map[string]any, adminInfo *AuditAdminInfo, auditInfo *AuditRequestInfo, request ...*gin.Context) { username, _ := GetUsernameById(logUserId, false) other := AuditOther{ Op: &AuditOperation{Action: action, Params: params}, @@ -252,7 +252,7 @@ func RecordOperationAuditLog(logUserId, actorRole int, content string, ip string func RecordTopupLog(userId int, content string, callerIp string, paymentMethod string, callbackPaymentMethod string) { username, _ := GetUsernameById(userId, false) other := NewLogOther() - other.MergeAdmin(map[string]interface{}{ + other.MergeAdmin(map[string]any{ "server_ip": common.GetIp(), "node_name": common.NodeName, "caller_ip": callerIp, diff --git a/model/log_format_test.go b/model/log_format_test.go index b34f09cada..b34a553f94 100644 --- a/model/log_format_test.go +++ b/model/log_format_test.go @@ -13,10 +13,10 @@ import ( // saturation marker (nested under other.admin_info) is removed for non-admin // log views, since formatUserLogs strips the whole admin_info object. func TestFormatUserLogsStripsQuotaSaturation(t *testing.T) { - other := common.MapToJsonStr(map[string]interface{}{ + other := common.MapToJsonStr(map[string]any{ "model_price": 0.004, - "admin_info": map[string]interface{}{ - "quota_saturation": map[string]interface{}{ + "admin_info": map[string]any{ + "quota_saturation": map[string]any{ "op": "QuotaFromDecimal", "kind": "overflow", "clamped": common.MaxQuota, @@ -36,18 +36,18 @@ func TestFormatUserLogsStripsQuotaSaturation(t *testing.T) { } func TestTaskPluginLogVisibilityIsRoleSeparated(t *testing.T) { - other := common.MapToJsonStr(map[string]interface{}{ + other := common.MapToJsonStr(map[string]any{ "model_price": 1.25, - "admin_info": map[string]interface{}{ - "task_plugin": map[string]interface{}{ + "admin_info": map[string]any{ + "task_plugin": map[string]any{ "key": "document-parser", "name": "Document Parser", "version": "1.2.3", }, }, - "root_info": map[string]interface{}{ + "root_info": map[string]any{ "upstream_task_id": "upstream-private", - "task_plugin": map[string]interface{}{ + "task_plugin": map[string]any{ "generation": 42, }, }, @@ -86,19 +86,19 @@ func TestTaskPluginLogVisibilityIsRoleSeparated(t *testing.T) { } func TestLegacyLogOtherVisibilityIsRoleSeparated(t *testing.T) { - other := common.MapToJsonStr(map[string]interface{}{ + other := common.MapToJsonStr(map[string]any{ "request_path": "/v1/chat/completions", "channel_id": 202, "channel_name": "legacy-secret-channel", "channel_type": 1, "reject_reason": "legacy-policy-rejection", - "admin_info": map[string]interface{}{ + "admin_info": map[string]any{ "existing_admin_field": "preserved", }, - "root_info": map[string]interface{}{ + "root_info": map[string]any{ "upstream_request_id": "upstream-private", }, - "audit_info": map[string]interface{}{ + "audit_info": map[string]any{ "method": "POST", }, }) @@ -143,7 +143,7 @@ func TestLegacyLogOtherVisibilityIsRoleSeparated(t *testing.T) { assert.NotContains(t, parsed, "reject_reason") assert.NotContains(t, parsed, "root_info") assert.Contains(t, parsed, "audit_info") - adminInfo, ok := parsed["admin_info"].(map[string]interface{}) + adminInfo, ok := parsed["admin_info"].(map[string]any) require.True(t, ok) assert.Equal(t, "preserved", adminInfo["existing_admin_field"]) assert.Equal(t, "legacy-policy-rejection", adminInfo["reject_reason"]) @@ -160,7 +160,7 @@ func TestLegacyLogOtherVisibilityIsRoleSeparated(t *testing.T) { assert.NotContains(t, parsed, "reject_reason") assert.Contains(t, parsed, "root_info") assert.Contains(t, parsed, "audit_info") - adminInfo, ok := parsed["admin_info"].(map[string]interface{}) + adminInfo, ok := parsed["admin_info"].(map[string]any) require.True(t, ok) assert.Equal(t, "preserved", adminInfo["existing_admin_field"]) assert.Equal(t, "legacy-policy-rejection", adminInfo["reject_reason"]) @@ -168,9 +168,9 @@ func TestLegacyLogOtherVisibilityIsRoleSeparated(t *testing.T) { } func TestLegacyRejectReasonDoesNotOverrideScopedValue(t *testing.T) { - other := common.MapToJsonStr(map[string]interface{}{ + other := common.MapToJsonStr(map[string]any{ "reject_reason": "legacy-value", - "admin_info": map[string]interface{}{ + "admin_info": map[string]any{ "reject_reason": "scoped-value", }, }) @@ -181,7 +181,7 @@ func TestLegacyRejectReasonDoesNotOverrideScopedValue(t *testing.T) { parsed, err := common.StrToMap(logs[0].Other) require.NoError(t, err) assert.NotContains(t, parsed, "reject_reason") - adminInfo, ok := parsed["admin_info"].(map[string]interface{}) + adminInfo, ok := parsed["admin_info"].(map[string]any) require.True(t, ok) assert.Equal(t, "scoped-value", adminInfo["reject_reason"]) } @@ -194,7 +194,7 @@ func TestLegacyRejectReasonHandlesNullAdminInfo(t *testing.T) { parsed, err := common.StrToMap(logs[0].Other) require.NoError(t, err) assert.NotContains(t, parsed, "reject_reason") - adminInfo, ok := parsed["admin_info"].(map[string]interface{}) + adminInfo, ok := parsed["admin_info"].(map[string]any) require.True(t, ok) assert.Equal(t, "legacy-value", adminInfo["reject_reason"]) } diff --git a/model/log_other_test.go b/model/log_other_test.go index 9ffaab0bb3..8bd2be0748 100644 --- a/model/log_other_test.go +++ b/model/log_other_test.go @@ -11,19 +11,19 @@ func TestLogOtherScopesAndMerges(t *testing.T) { var other LogOther assert.True(t, other.SetPublic("request_path", "/v1/chat/completions")) - other.MergePublic(map[string]interface{}{ + other.MergePublic(map[string]any{ "zero": 0, }) assert.True(t, other.SetAdmin("use_channel", []string{"channel-a"})) - other.MergeAdmin(map[string]interface{}{ + other.MergeAdmin(map[string]any{ "rejected": false, }) assert.True(t, other.SetRoot("upstream_request_id", "upstream-private")) - other.MergeRoot(map[string]interface{}{ + other.MergeRoot(map[string]any{ "generation": 0, }) assert.True(t, other.SetAudit("method", "POST")) - other.MergeAudit(map[string]interface{}{ + other.MergeAudit(map[string]any{ "success": false, }) @@ -59,10 +59,10 @@ func TestLogOtherRejectsSensitivePublicFields(t *testing.T) { } { assert.False(t, other.SetPublic(key, "must-not-leak"), key) } - other.MergePublic(map[string]interface{}{ + other.MergePublic(map[string]any{ "request_path": "/v1/responses", "channel_name": "still-must-not-leak", - "admin_info": map[string]interface{}{"secret": true}, + "admin_info": map[string]any{"secret": true}, }) require.JSONEq(t, `{"request_path":"/v1/responses"}`, other.JSONString()) diff --git a/model/main.go b/model/main.go index 19c237738d..f2a26fcf94 100644 --- a/model/main.go +++ b/model/main.go @@ -29,7 +29,7 @@ var logGroupCol string // jsonScanBytes 归一化 json 列的驱动返回值:不同驱动/协议模式下同一列可能 // 以 []byte 或 string 返回,静默丢弃 string 会导致字段被清零而不报错。 -func jsonScanBytes(value interface{}) []byte { +func jsonScanBytes(value any) []byte { switch v := value.(type) { case []byte: return v diff --git a/model/model_pricing_config.go b/model/model_pricing_config.go index dbfcd42ff8..4014a9fea5 100644 --- a/model/model_pricing_config.go +++ b/model/model_pricing_config.go @@ -5,6 +5,7 @@ import ( "errors" "fmt" "math" + "slices" "sort" "strings" "sync" @@ -56,12 +57,7 @@ var modelPricingOptionKeys = []string{ var modelPricingMutationMu sync.Mutex func IsModelPricingOption(key string) bool { - for _, candidate := range modelPricingOptionKeys { - if key == candidate { - return true - } - } - return false + return slices.Contains(modelPricingOptionKeys, key) } func ModelPricingVersion(values PricingValues) string { diff --git a/model/option.go b/model/option.go index ca5f4841b6..1852d4404e 100644 --- a/model/option.go +++ b/model/option.go @@ -1,6 +1,7 @@ package model import ( + "maps" "strconv" "strings" "time" @@ -187,9 +188,7 @@ func InitOptionMap() { // 自动添加所有注册的模型配置 modelConfigs := config.GlobalConfig.ExportAllConfigs() - for k, v := range modelConfigs { - common.OptionMap[k] = v - } + maps.Copy(common.OptionMap, modelConfigs) common.OptionMapRWMutex.Unlock() loadOptionsFromDatabase() diff --git a/model/passkey.go b/model/passkey.go index aabaad646b..b38cbda293 100644 --- a/model/passkey.go +++ b/model/passkey.go @@ -168,7 +168,7 @@ func UpdatePasskeyAssertionState(userID int, credential *webauthn.Credential, la credentialID := base64.StdEncoding.EncodeToString(credential.ID) result := DB.Model(&PasskeyCredential{}). Where("user_id = ? AND credential_id = ?", userID, credentialID). - Updates(map[string]interface{}{ + Updates(map[string]any{ "sign_count": credential.Authenticator.SignCount, "clone_warning": credential.Authenticator.CloneWarning, "user_present": credential.Flags.UserPresent, diff --git a/model/perf_metric.go b/model/perf_metric.go index f9c33c8519..f1ae6f941b 100644 --- a/model/perf_metric.go +++ b/model/perf_metric.go @@ -36,7 +36,7 @@ func UpsertPerfMetric(metric *PerfMetric) error { {Name: "group"}, {Name: "bucket_ts"}, }, - DoUpdates: clause.Assignments(map[string]interface{}{ + DoUpdates: clause.Assignments(map[string]any{ "request_count": gorm.Expr("perf_metrics.request_count + ?", metric.RequestCount), "success_count": gorm.Expr("perf_metrics.success_count + ?", metric.SuccessCount), "total_latency_ms": gorm.Expr("perf_metrics.total_latency_ms + ?", metric.TotalLatencyMs), diff --git a/model/prefill_group.go b/model/prefill_group.go index 0d3e3d1ef0..a50db1ec2b 100644 --- a/model/prefill_group.go +++ b/model/prefill_group.go @@ -30,7 +30,7 @@ func (j JSONValue) Value() (driver.Value, error) { } // Scan 实现 sql.Scanner 接口,兼容不同驱动返回的类型 -func (j *JSONValue) Scan(value interface{}) error { +func (j *JSONValue) Scan(value any) error { switch v := value.(type) { case nil: *j = nil diff --git a/model/pricing.go b/model/pricing.go index aad8b633ea..a88934aab2 100644 --- a/model/pricing.go +++ b/model/pricing.go @@ -251,12 +251,12 @@ func updatePricing() { if strings.TrimSpace(meta.Endpoints) == "" { continue } - var raw map[string]interface{} + var raw map[string]any if err := common.Unmarshal([]byte(meta.Endpoints), &raw); err == nil { endpoints := modelSupportEndpointsStr[modelName] for k, v := range raw { switch v.(type) { - case string, map[string]interface{}: + case string, map[string]any: endpoints = appendPricingEndpoint(endpoints, k) } } @@ -293,13 +293,13 @@ func updatePricing() { if strings.TrimSpace(meta.Endpoints) == "" { continue } - var raw map[string]interface{} + var raw map[string]any if err := common.Unmarshal([]byte(meta.Endpoints), &raw); err == nil { for k, v := range raw { switch val := v.(type) { case string: supportedEndpointMap[k] = common.EndpointInfo{Path: val, Method: "POST"} - case map[string]interface{}: + case map[string]any: ep := common.EndpointInfo{Method: "POST"} if p, ok := val["path"].(string); ok { ep.Path = p @@ -399,9 +399,7 @@ func updatePricing() { pricing.BillingUsageExamples = make([]jsplugin.UsageExample, len(plugin.Meta.UsageExamples)) for index, example := range plugin.Meta.UsageExamples { facts := make(map[string]any, len(example.Facts)) - for key, value := range example.Facts { - facts[key] = value - } + maps.Copy(facts, example.Facts) pricing.BillingUsageExamples[index] = jsplugin.UsageExample{ Label: example.Label, Facts: facts, diff --git a/model/quota_reserve.go b/model/quota_reserve.go index 37051f7e78..a00e0509b0 100644 --- a/model/quota_reserve.go +++ b/model/quota_reserve.go @@ -126,7 +126,7 @@ func persistTokenQuotaDelta(id int, delta int) error { return nil } result := DB.Model(&Token{}).Where("id = ?", id).Updates( - map[string]interface{}{ + map[string]any{ "remain_quota": gorm.Expr("remain_quota + ?", delta), "used_quota": gorm.Expr("used_quota - ?", delta), "accessed_time": common.GetTimestamp(), @@ -151,7 +151,7 @@ func reserveUserQuotaDB(id int, quota int) (bool, error) { func reserveTokenQuotaDB(id int, quota int) (bool, error) { result := DB.Model(&Token{}). Where("id = ? AND remain_quota >= ?", id, quota). - Updates(map[string]interface{}{ + Updates(map[string]any{ "remain_quota": gorm.Expr("remain_quota - ?", quota), "used_quota": gorm.Expr("used_quota + ?", quota), "accessed_time": common.GetTimestamp(), diff --git a/model/quota_reserve_test.go b/model/quota_reserve_test.go index 865f73ed67..6c0de1f05c 100644 --- a/model/quota_reserve_test.go +++ b/model/quota_reserve_test.go @@ -59,14 +59,14 @@ func resetBatchUpdateTestState(t *testing.T) { t.Helper() oldBatchEnabled := common.BatchUpdateEnabled common.BatchUpdateEnabled = false - for i := 0; i < BatchUpdateTypeCount; i++ { + for i := range BatchUpdateTypeCount { batchUpdateLocks[i].Lock() batchUpdateStores[i] = make(map[int]int) batchUpdateLocks[i].Unlock() } t.Cleanup(func() { common.BatchUpdateEnabled = oldBatchEnabled - for i := 0; i < BatchUpdateTypeCount; i++ { + for i := range BatchUpdateTypeCount { batchUpdateLocks[i].Lock() batchUpdateStores[i] = make(map[int]int) batchUpdateLocks[i].Unlock() diff --git a/model/redemption.go b/model/redemption.go index 96f8aebc53..e12d88ee47 100644 --- a/model/redemption.go +++ b/model/redemption.go @@ -164,7 +164,7 @@ func Redeem(key string, userId int) (quota int, err error) { // same code loses here even without a row lock (e.g. on SQLite). result := tx.Model(&Redemption{}). Where("id = ? AND status = ?", redemption.Id, common.RedemptionCodeStatusEnabled). - Updates(map[string]interface{}{ + Updates(map[string]any{ "redeemed_time": common.GetTimestamp(), "status": common.RedemptionCodeStatusUsed, "used_user_id": userId, diff --git a/model/redemption_test.go b/model/redemption_test.go index 0150fc19e3..9f883f25c1 100644 --- a/model/redemption_test.go +++ b/model/redemption_test.go @@ -186,7 +186,7 @@ func TestRedeemConcurrentSingleSuccess(t *testing.T) { successes := make([]bool, goroutines) var wg sync.WaitGroup wg.Add(goroutines) - for i := 0; i < goroutines; i++ { + for i := range goroutines { go func(idx int) { defer wg.Done() if _, err := Redeem(key, userId); err == nil { diff --git a/model/subscription.go b/model/subscription.go index 769d7b94a8..4438dfe07b 100644 --- a/model/subscription.go +++ b/model/subscription.go @@ -939,7 +939,7 @@ func AdminInvalidateUserSubscription(userSubscriptionId int) (string, error) { return err } userId = sub.UserId - if err := tx.Model(&sub).Updates(map[string]interface{}{ + if err := tx.Model(&sub).Updates(map[string]any{ "status": "cancelled", "end_time": now, "updated_at": now, @@ -1164,7 +1164,7 @@ func ExpireDueSubscriptions(limit int) (int, error) { err := DB.Transaction(func(tx *gorm.DB) error { res := tx.Model(&UserSubscription{}). Where("user_id = ? AND status = ? AND end_time > 0 AND end_time <= ?", userId, "active", now). - Updates(map[string]interface{}{ + Updates(map[string]any{ "status": "expired", "updated_at": common.GetTimestamp(), }) @@ -1521,10 +1521,7 @@ func PostConsumeUserSubscriptionDelta(userSubscriptionId int, delta int64) error First(&sub).Error; err != nil { return err } - newUsed := sub.AmountUsed + delta - if newUsed < 0 { - newUsed = 0 - } + newUsed := max(sub.AmountUsed+delta, 0) if sub.AmountTotal > 0 && newUsed > sub.AmountTotal { return fmt.Errorf("subscription used exceeds total, used=%d total=%d", newUsed, sub.AmountTotal) } diff --git a/model/task.go b/model/task.go index 72e6f60731..34ff2f4973 100644 --- a/model/task.go +++ b/model/task.go @@ -86,7 +86,7 @@ type Properties struct { OriginModelName string `json:"origin_model_name,omitempty"` } -func (m *Properties) Scan(val interface{}) error { +func (m *Properties) Scan(val any) error { bytesValue := jsonScanBytes(val) if len(bytesValue) == 0 { *m = Properties{} @@ -190,7 +190,7 @@ func GenerateTaskID() string { return "task_" + key } -func (p *TaskPrivateData) Scan(val interface{}) error { +func (p *TaskPrivateData) Scan(val any) error { bytesValue := jsonScanBytes(val) if len(bytesValue) == 0 { return nil diff --git a/model/task_cas_test.go b/model/task_cas_test.go index 264892f0ce..1bc00e9531 100644 --- a/model/task_cas_test.go +++ b/model/task_cas_test.go @@ -289,7 +289,7 @@ func TestUpdateWithStatus_ConcurrentWinner(t *testing.T) { var wg sync.WaitGroup wg.Add(goroutines) - for i := 0; i < goroutines; i++ { + for i := range goroutines { go func(idx int) { defer wg.Done() t := &Task{} diff --git a/model/token.go b/model/token.go index 95cbabae6d..bd2d5bf19d 100644 --- a/model/token.go +++ b/model/token.go @@ -92,8 +92,8 @@ func (token *Token) GetIpLimits() []string { if cleanIps == "" { return ipLimits } - ips := strings.Split(cleanIps, "\n") - for _, ip := range ips { + ips := strings.SplitSeq(cleanIps, "\n") + for ip := range ips { ip = strings.TrimSpace(ip) ip = strings.ReplaceAll(ip, ",", "") if ip != "" { @@ -396,7 +396,7 @@ func IncreaseTokenQuota(tokenId int, key string, quota int) (err error) { func increaseTokenQuota(id int, quota int) (err error) { err = DB.Model(&Token{}).Where("id = ?", id).Updates( - map[string]interface{}{ + map[string]any{ "remain_quota": gorm.Expr("remain_quota + ?", quota), "used_quota": gorm.Expr("used_quota - ?", quota), "accessed_time": common.GetTimestamp(), @@ -425,7 +425,7 @@ func DecreaseTokenQuota(id int, key string, quota int) (err error) { func decreaseTokenQuota(id int, quota int) (err error) { err = DB.Model(&Token{}).Where("id = ?", id).Updates( - map[string]interface{}{ + map[string]any{ "remain_quota": gorm.Expr("remain_quota - ?", quota), "used_quota": gorm.Expr("used_quota + ?", quota), "accessed_time": common.GetTimestamp(), diff --git a/model/topup.go b/model/topup.go index a8b91b7750..9e031d0f42 100644 --- a/model/topup.go +++ b/model/topup.go @@ -3,6 +3,7 @@ package model import ( "errors" "fmt" + "maps" "github.com/QuantumNous/new-api/common" "github.com/QuantumNous/new-api/logger" @@ -85,16 +86,14 @@ func ValidateTopUpQuotaCapacity(userId int, creditedQuota int) error { // creditTopUpQuota atomically enforces the wallet ceiling while adding quota. // Keeping the predicate and increment in one UPDATE prevents two // concurrent callbacks from both passing a separate read/check. -func creditTopUpQuota(tx *gorm.DB, userId int, creditedQuota int, updates map[string]interface{}) error { +func creditTopUpQuota(tx *gorm.DB, userId int, creditedQuota int, updates map[string]any) error { maxCurrentQuota, err := topUpQuotaMaxCurrent(creditedQuota) if err != nil { return err } - updateFields := make(map[string]interface{}, len(updates)+1) - for key, value := range updates { - updateFields[key] = value - } + updateFields := make(map[string]any, len(updates)+1) + maps.Copy(updateFields, updates) updateFields["quota"] = gorm.Expr("quota + ?", creditedQuota) result := tx.Model(&User{}). @@ -273,7 +272,7 @@ func Recharge(referenceId string, customerId string, callerIp string) (err error if err != nil || quota <= 0 { return ErrInvalidTopUpQuota } - return creditTopUpQuota(tx, topUp.UserId, quota, map[string]interface{}{ + return creditTopUpQuota(tx, topUp.UserId, quota, map[string]any{ "stripe_customer": customerId, }) }) @@ -563,7 +562,7 @@ func RechargeCreem(referenceId string, customerEmail string, customerName string } // 构建更新字段,优先使用邮箱,如果邮箱为空则使用用户名 - updateFields := map[string]interface{}{} + updateFields := map[string]any{} // 如果有客户邮箱,尝试更新用户邮箱(仅当用户邮箱为空时) if customerEmail != "" { diff --git a/model/twofa.go b/model/twofa.go index 3427745ccc..d1d050ef17 100644 --- a/model/twofa.go +++ b/model/twofa.go @@ -66,7 +66,7 @@ func (t *TwoFA) updateUsageState() error { if t.Id == 0 { return errors.New("2FA记录ID不能为空") } - return DB.Model(&TwoFA{}).Where("id = ?", t.Id).Updates(map[string]interface{}{ + return DB.Model(&TwoFA{}).Where("id = ?", t.Id).Updates(map[string]any{ "failed_attempts": t.FailedAttempts, "locked_until": t.LockedUntil, "last_used_at": t.LastUsedAt, @@ -109,7 +109,7 @@ func (t *TwoFA) IncrementFailedAttempts() error { result := DB.Model(&TwoFA{}). Where("id = ? AND failed_attempts = ? AND (locked_until IS NULL OR locked_until <= ?)", current.Id, current.FailedAttempts, now). - Updates(map[string]interface{}{ + Updates(map[string]any{ "failed_attempts": nextFailedAttempts, "locked_until": nextLockedUntil, }) @@ -208,7 +208,7 @@ func ValidateBackupCode(userId int, code string) (bool, error) { now := time.Now() result := DB.Model(&TwoFABackupCode{}). Where("id = ? AND is_used = ?", bc.Id, false). - Updates(map[string]interface{}{ + Updates(map[string]any{ "is_used": true, "used_at": now, }) @@ -332,7 +332,7 @@ func (t *TwoFA) ValidateBackupCodeAndUpdateUsage(code string) (bool, error) { } // GetTwoFAStats 获取2FA统计信息(管理员使用) -func GetTwoFAStats() (map[string]interface{}, error) { +func GetTwoFAStats() (map[string]any, error) { var totalUsers, enabledUsers int64 // 总用户数 @@ -350,7 +350,7 @@ func GetTwoFAStats() (map[string]interface{}, error) { enabledRate = float64(enabledUsers) / float64(totalUsers) * 100 } - return map[string]interface{}{ + return map[string]any{ "total_users": totalUsers, "enabled_users": enabledUsers, "enabled_rate": fmt.Sprintf("%.1f%%", enabledRate), diff --git a/model/usedata.go b/model/usedata.go index 4190235bc2..266fd88b1c 100644 --- a/model/usedata.go +++ b/model/usedata.go @@ -128,7 +128,7 @@ func increaseQuotaData(quotaData *QuotaData) { err := DB.Table("quota_data"). Where("user_id = ? and username = ? and model_name = ? and created_at = ? and use_group = ? and token_id = ? and channel_id = ? and node_name = ?", quotaData.UserID, quotaData.Username, quotaData.ModelName, quotaData.CreatedAt, quotaData.UseGroup, quotaData.TokenID, quotaData.ChannelID, quotaData.NodeName). - Updates(map[string]interface{}{ + Updates(map[string]any{ "count": gorm.Expr("count + ?", quotaData.Count), "quota": gorm.Expr("quota + ?", quotaData.Quota), "token_used": gorm.Expr("token_used + ?", quotaData.TokenUsed), diff --git a/model/user.go b/model/user.go index 501aed8963..1a70459337 100644 --- a/model/user.go +++ b/model/user.go @@ -147,7 +147,7 @@ func UpdateUserAccessToken(id int, token string) error { if id == 0 { return errors.New("id 为空!") } - result := DB.Model(&User{}).Where("id = ?", id).Updates(map[string]interface{}{ + result := DB.Model(&User{}).Where("id = ?", id).Updates(map[string]any{ "access_token": token, "access_token_created_at": common.GetTimestamp(), }) if result.Error != nil { @@ -171,7 +171,7 @@ func RevokeUserAccessToken(id int) (string, error) { if tokenRef == "" { return nil } - return tx.Model(&User{}).Where("id = ?", id).Updates(map[string]interface{}{"access_token": nil, "access_token_created_at": nil}).Error + return tx.Model(&User{}).Where("id = ?", id).Updates(map[string]any{"access_token": nil, "access_token_created_at": nil}).Error }) return tokenRef, err } @@ -237,17 +237,17 @@ func UpdateUserBindColumn(userId int, column string, value string) error { // 根据用户角色生成默认的边栏配置 func generateDefaultSidebarConfigForRole(userRole int) string { - defaultConfig := map[string]interface{}{} + defaultConfig := map[string]any{} // 聊天区域 - 所有用户都可以访问 - defaultConfig["chat"] = map[string]interface{}{ + defaultConfig["chat"] = map[string]any{ "enabled": true, "playground": true, "chat": true, } // 控制台区域 - 所有用户都可以访问 - defaultConfig["console"] = map[string]interface{}{ + defaultConfig["console"] = map[string]any{ "enabled": true, "detail": true, "token": true, @@ -257,7 +257,7 @@ func generateDefaultSidebarConfigForRole(userRole int) string { } // 个人中心区域 - 所有用户都可以访问 - defaultConfig["personal"] = map[string]interface{}{ + defaultConfig["personal"] = map[string]any{ "enabled": true, "topup": true, "personal": true, @@ -266,7 +266,7 @@ func generateDefaultSidebarConfigForRole(userRole int) string { // 管理员区域 - 根据角色决定 if userRole == common.RoleAdminUser { // 管理员可以访问管理员区域,但不能访问系统设置 - defaultConfig["admin"] = map[string]interface{}{ + defaultConfig["admin"] = map[string]any{ "enabled": true, "channel": true, "models": true, @@ -276,7 +276,7 @@ func generateDefaultSidebarConfigForRole(userRole int) string { } } else if userRole == common.RoleRootUser { // 超级管理员可以访问所有功能 - defaultConfig["admin"] = map[string]interface{}{ + defaultConfig["admin"] = map[string]any{ "enabled": true, "channel": true, "models": true, @@ -470,14 +470,14 @@ func SearchUsers(keyword string, group string, role *int, status *int, startIdx // 构建搜索条件 likeCondition := "username LIKE ? OR email LIKE ? OR display_name LIKE ?" - likeArgs := []interface{}{"%" + keyword + "%", "%" + keyword + "%", "%" + keyword + "%"} + likeArgs := []any{"%" + keyword + "%", "%" + keyword + "%", "%" + keyword + "%"} // 尝试将关键字转换为整数ID keywordInt, err := strconv.Atoi(keyword) if err == nil { // 如果是数字,同时搜索ID和其他字段 likeCondition = "id = ? OR " + likeCondition - likeArgs = append([]interface{}{keywordInt}, likeArgs...) + likeArgs = append([]any{keywordInt}, likeArgs...) } query = query.Where("("+likeCondition+")", likeArgs...) @@ -580,7 +580,7 @@ func HardDeleteUserById(id int) error { } func inviteUser(inviterId int) error { - result := DB.Model(&User{}).Where("id = ?", inviterId).Updates(map[string]interface{}{ + result := DB.Model(&User{}).Where("id = ?", inviterId).Updates(map[string]any{ "aff_count": gorm.Expr("aff_count + ?", 1), "aff_quota": gorm.Expr("aff_quota + ?", common.QuotaForInviter), "aff_history": gorm.Expr("aff_history + ?", common.QuotaForInviter), @@ -887,7 +887,7 @@ func (user *User) EditWithTx(tx *gorm.DB, updatePassword bool) error { } newUser := *user - updates := map[string]interface{}{ + updates := map[string]any{ "username": newUser.Username, "display_name": newUser.DisplayName, "group": newUser.Group, @@ -1459,7 +1459,7 @@ func UpdateUserUsedQuota(id int, quota int) { func updateUserUsedQuotaAndRequestCount(id int, quota int, count int) { err := DB.Model(&User{}).Where("id = ?", id).Updates( - map[string]interface{}{ + map[string]any{ "used_quota": gorm.Expr("used_quota + ?", quota), "request_count": gorm.Expr("request_count + ?", count), }, @@ -1481,7 +1481,7 @@ func updateUserQuotaUsedQuotaAndRequestCount(id int, quota int, usedQuota int, r } err := DB.Model(&User{}).Where("id = ?", id).Updates( - map[string]interface{}{ + map[string]any{ "quota": gorm.Expr("quota + ?", quota), "used_quota": gorm.Expr("used_quota + ?", usedQuota), "request_count": gorm.Expr("request_count + ?", requestCount), diff --git a/model/user_auth_cache.go b/model/user_auth_cache.go index d2cdc8a7cc..a657f786af 100644 --- a/model/user_auth_cache.go +++ b/model/user_auth_cache.go @@ -38,10 +38,7 @@ func getUserAuthVersionKey(userId int) string { // recover without an operator repairing Redis. func userAuthFenceTTLSeconds() int { cacheTTL := userCacheTTLSeconds() - extra := cacheTTL - if extra < 60 { - extra = 60 - } + extra := max(cacheTTL, 60) return cacheTTL + extra } @@ -186,10 +183,7 @@ func IncrementUserAuthVersionWithTx(tx *gorm.DB, userId int) (int64, error) { if err := lockForUpdate(tx.Unscoped()).Select("id", "auth_version").Where("id = ?", userId).First(&user).Error; err != nil { return 0, err } - current := user.AuthVersion - if current < 1 { - current = 1 - } + current := max(user.AuthVersion, 1) next := current + 1 if err := SetUserAuthVersionFence(userId, next); err != nil { return 0, err @@ -240,7 +234,7 @@ func InitializeUserAuthVersions() error { return DB.Model(&User{}).Where("auth_version IS NULL OR auth_version < ?", 1).Update("auth_version", 1).Error } -func updateUserCacheFieldAtVersion(userId int, field string, value interface{}, authVersion int64) error { +func updateUserCacheFieldAtVersion(userId int, field string, value any, authVersion int64) error { if !common.RedisEnabled { return nil } diff --git a/model/user_authentication_test.go b/model/user_authentication_test.go index 571c9bd482..6f5149969e 100644 --- a/model/user_authentication_test.go +++ b/model/user_authentication_test.go @@ -142,11 +142,9 @@ func TestIncrementFailedAttemptsCountsConcurrentFailures(t *testing.T) { errs := make(chan error, attempts) var wg sync.WaitGroup for range attempts { - wg.Add(1) - go func() { - defer wg.Done() + wg.Go(func() { errs <- (&TwoFA{Id: twoFA.Id}).IncrementFailedAttempts() - }() + }) } wg.Wait() close(errs) @@ -175,13 +173,11 @@ func TestValidateBackupCodeCanOnlySucceedOnce(t *testing.T) { errs := make(chan error, attempts) var wg sync.WaitGroup for range attempts { - wg.Add(1) - go func() { - defer wg.Done() + wg.Go(func() { valid, err := ValidateBackupCode(123, code) results <- valid errs <- err - }() + }) } wg.Wait() close(results) diff --git a/model/user_cache.go b/model/user_cache.go index e8996e9be1..2dc6219dd6 100644 --- a/model/user_cache.go +++ b/model/user_cache.go @@ -253,7 +253,7 @@ func updateUserSettingCache(userId int, setting string) error { // updateUserCacheField prevents individual cache refreshes from bypassing the // auth-version fence. It intentionally does nothing when the complete hash is // absent; the next GetUserCache call will repopulate it from the database. -func updateUserCacheField(userId int, field string, value interface{}) error { +func updateUserCacheField(userId int, field string, value any) error { if !common.RedisEnabled { return nil } diff --git a/model/user_session.go b/model/user_session.go index 8857aaf207..8b20785994 100644 --- a/model/user_session.go +++ b/model/user_session.go @@ -481,7 +481,7 @@ func RotateUserSessionRefresh(userID int, sid, presentedHash, nextHash string, n result := DB.Model(&UserSession{}). Where("sid = ? AND user_id = ? AND status = ? AND revoked_at = ? AND expires_at > ? AND refresh_hash = ?", sid, userID, UserSessionStatusActive, 0, now, presentedHash). - Updates(map[string]interface{}{ + Updates(map[string]any{ "previous_refresh_hash": session.RefreshHash, "previous_valid_until": now + graceSeconds, "refresh_hash": nextHash, @@ -527,7 +527,7 @@ func RotateUserSessionRefresh(userID int, sid, presentedHash, nextHash string, n result := DB.Model(&UserSession{}). Where("sid = ? AND user_id = ? AND status = ? AND revoked_at = ? AND expires_at > ?", sid, userID, UserSessionStatusActive, 0, now). - Updates(map[string]interface{}{ + Updates(map[string]any{ "status": UserSessionStatusRevoked, "revoked_at": now, "revoked_reason": "refresh_reuse", @@ -577,7 +577,7 @@ func RevokeUserSession(userID int, sid, reason string) (bool, error) { if current.Status != UserSessionStatusActive || current.RevokedAt != 0 || current.ExpiresAt <= now { return nil } - result := tx.Model(&UserSession{}).Where("sid = ? AND status = ?", sid, UserSessionStatusActive).Updates(map[string]interface{}{ + result := tx.Model(&UserSession{}).Where("sid = ? AND status = ?", sid, UserSessionStatusActive).Updates(map[string]any{ "status": UserSessionStatusRevoked, "revoked_at": now, "revoked_reason": reason, @@ -631,7 +631,7 @@ func RevokeUserSessionByRefreshHash(sid, presentedHash, reason string) (bool, er if err := writeUserSessionDenyFence(&session, UserSessionStatusRevoking, now, reason); err != nil { return err } - result := tx.Model(&UserSession{}).Where("sid = ? AND status = ?", sid, UserSessionStatusActive).Updates(map[string]interface{}{ + result := tx.Model(&UserSession{}).Where("sid = ? AND status = ?", sid, UserSessionStatusActive).Updates(map[string]any{ "status": UserSessionStatusRevoked, "revoked_at": now, "revoked_reason": reason, @@ -681,7 +681,7 @@ func AdvanceUserSessionAuthVersion(userID int, sid string, expectedSessionVersio session.LastActiveAt = now result := tx.Model(&UserSession{}). Where("sid = ? AND status = ? AND version = ? AND user_auth_version = ?", sid, UserSessionStatusActive, expectedSessionVersion, expectedUserAuthVersion). - Updates(map[string]interface{}{ + Updates(map[string]any{ "version": session.Version, "user_auth_version": session.UserAuthVersion, "last_active_at": session.LastActiveAt, @@ -758,7 +758,7 @@ func revokeUserSessions(userID int, excludedSID, reason string) (int64, error) { for i := range revoked { lockedSIDs = append(lockedSIDs, revoked[i].SID) } - result := tx.Model(&UserSession{}).Where("sid IN ? AND status = ?", lockedSIDs, UserSessionStatusActive).Updates(map[string]interface{}{ + result := tx.Model(&UserSession{}).Where("sid IN ? AND status = ?", lockedSIDs, UserSessionStatusActive).Updates(map[string]any{ "status": UserSessionStatusRevoked, "revoked_at": now, "revoked_reason": reason, @@ -823,10 +823,7 @@ func deleteExpiredUserSessionsBefore(expiredBefore, issuanceCutoff, revokedBefor return nil } for start := 0; start < len(sids); start += userSessionCleanupBatchSize { - end := start + userSessionCleanupBatchSize - if end > len(sids) { - end = len(sids) - } + end := min(start+userSessionCleanupBatchSize, len(sids)) if err := DB.Where("sid IN ?", sids[start:end]). Where( "expires_at < ? AND created_at <= ? AND (status <> ? OR revoked_at <= 0 OR revoked_at < ?)", @@ -859,10 +856,7 @@ func deleteRevokedUserSessionsBefore(revokedBefore, issuanceCutoff int64) error return nil } for start := 0; start < len(sids); start += userSessionCleanupBatchSize { - end := start + userSessionCleanupBatchSize - if end > len(sids) { - end = len(sids) - } + end := min(start+userSessionCleanupBatchSize, len(sids)) if err := DB.Where("sid IN ?", sids[start:end]). Where( "status = ? AND revoked_at > 0 AND revoked_at < ? AND created_at <= ?", diff --git a/model/user_session_test.go b/model/user_session_test.go index e9e4e1b21d..cce47a1511 100644 --- a/model/user_session_test.go +++ b/model/user_session_test.go @@ -432,7 +432,7 @@ func TestListActiveUserSessionsKeepsCurrentAndBoundsOtherSessions(t *testing.T) current.UserAuthVersion = 7 rows := make([]UserSession, 0, 107) rows = append(rows, *current) - for i := 0; i < 105; i++ { + for i := range 105 { session := newTestUserSession(fmt.Sprintf("list-other-%03d", i), 1007, now-int64(i)) session.UserAuthVersion = 7 rows = append(rows, *session) @@ -461,7 +461,7 @@ func TestRevokeUserSessionsReturnsCumulativeProgressAndSupportsRetry(t *testing. now := time.Now().Unix() createUserSessionTestUser(t, 1008, 1) rows := make([]UserSession, 0, userSessionRevokeBatchSize+1) - for i := 0; i < userSessionRevokeBatchSize+1; i++ { + for i := range userSessionRevokeBatchSize + 1 { rows = append(rows, *newTestUserSession(fmt.Sprintf("batch-revoke-%03d", i), 1008, now)) } require.NoError(t, DB.CreateInBatches(rows, 100).Error) @@ -509,7 +509,7 @@ func TestDeleteExpiredUserSessionsLoopsInChunksAndRechecksPredicate(t *testing.T race.CreatedAt = oldCreatedAt race.ExpiresAt = now - 1000 rows = append(rows, *race) - for i := 0; i < userSessionCleanupScanLimit+1; i++ { + for i := range userSessionCleanupScanLimit + 1 { session := newTestUserSession(fmt.Sprintf("cleanup-expired-%04d", i), 1009, now-100) session.CreatedAt = oldCreatedAt - int64(i) session.ExpiresAt = now - 100 diff --git a/model/user_update_test.go b/model/user_update_test.go index a0b6d914fe..1089d749fd 100644 --- a/model/user_update_test.go +++ b/model/user_update_test.go @@ -64,7 +64,7 @@ func TestUserUpdateDoesNotOverwriteConcurrentAccountingOrTokenChanges(t *testing staleUser, err := GetUserById(user.Id, true) require.NoError(t, err) - require.NoError(t, DB.Model(&User{}).Where("id = ?", user.Id).Updates(map[string]interface{}{ + require.NoError(t, DB.Model(&User{}).Where("id = ?", user.Id).Updates(map[string]any{ "quota": gorm.Expr("quota - ?", 400), "used_quota": gorm.Expr("used_quota + ?", 400), "request_count": gorm.Expr("request_count + ?", 1), @@ -159,7 +159,7 @@ func TestUpdateUserAccessTokenOnlyUpdatesAccessToken(t *testing.T) { } require.NoError(t, DB.Create(&user).Error) - require.NoError(t, DB.Model(&User{}).Where("id = ?", user.Id).Updates(map[string]interface{}{ + require.NoError(t, DB.Model(&User{}).Where("id = ?", user.Id).Updates(map[string]any{ "quota": gorm.Expr("quota + ?", 500), "aff_quota": gorm.Expr("aff_quota - ?", 500), "display_name": "concurrent-update", @@ -211,7 +211,7 @@ func TestUpdateUserSettingOnlyUpdatesSetting(t *testing.T) { } require.NoError(t, DB.Create(&user).Error) - require.NoError(t, DB.Model(&User{}).Where("id = ?", user.Id).Updates(map[string]interface{}{ + require.NoError(t, DB.Model(&User{}).Where("id = ?", user.Id).Updates(map[string]any{ "quota": gorm.Expr("quota - ?", 250), "used_quota": gorm.Expr("used_quota + ?", 250), "request_count": gorm.Expr("request_count + ?", 1), @@ -292,7 +292,7 @@ func TestUpdateUserBindColumnOnlyTouchesTheBindingColumn(t *testing.T) { truncateTables(t) user := createUserBindTestUser(t) - require.NoError(t, DB.Model(&User{}).Where("id = ?", user.Id).Updates(map[string]interface{}{ + require.NoError(t, DB.Model(&User{}).Where("id = ?", user.Id).Updates(map[string]any{ "role": common.RoleAdminUser, "status": common.UserStatusEnabled, "group": "vip", diff --git a/model/utils.go b/model/utils.go index 63d51c4b88..aef2f72108 100644 --- a/model/utils.go +++ b/model/utils.go @@ -26,7 +26,7 @@ var batchUpdateStores []map[int]int var batchUpdateLocks []sync.Mutex func init() { - for i := 0; i < BatchUpdateTypeCount; i++ { + for range BatchUpdateTypeCount { batchUpdateStores = append(batchUpdateStores, make(map[int]int)) batchUpdateLocks = append(batchUpdateLocks, sync.Mutex{}) } @@ -65,7 +65,7 @@ func addNewRecord(type_ int, id int, value int) { func batchUpdate() { // check if there's any data to update hasData := false - for i := 0; i < BatchUpdateTypeCount; i++ { + for i := range BatchUpdateTypeCount { batchUpdateLocks[i].Lock() if len(batchUpdateStores[i]) > 0 { hasData = true @@ -81,7 +81,7 @@ func batchUpdate() { common.SysLog("batch update started") stores := make([]map[int]int, BatchUpdateTypeCount) - for i := 0; i < BatchUpdateTypeCount; i++ { + for i := range BatchUpdateTypeCount { batchUpdateLocks[i].Lock() stores[i] = batchUpdateStores[i] batchUpdateStores[i] = make(map[int]int) diff --git a/oauth/registry.go b/oauth/registry.go index d5e5b4d795..b49a6ca8a3 100644 --- a/oauth/registry.go +++ b/oauth/registry.go @@ -2,6 +2,7 @@ package oauth import ( "fmt" + "maps" "sync" "github.com/QuantumNous/new-api/common" @@ -62,9 +63,7 @@ func GetAllProviders() map[string]Provider { mu.RLock() defer mu.RUnlock() result := make(map[string]Provider, len(providers)) - for k, v := range providers { - result[k] = v - } + maps.Copy(result, providers) return result } diff --git a/pkg/billingexpr/compile.go b/pkg/billingexpr/compile.go index 4421ce9bc0..6d0c8476af 100644 --- a/pkg/billingexpr/compile.go +++ b/pkg/billingexpr/compile.go @@ -122,7 +122,7 @@ var ( ) // compileEnvPrototypeV1 is the v1 type-checking prototype used at compile time. -var compileEnvPrototypeV1 = map[string]interface{}{ +var compileEnvPrototypeV1 = map[string]any{ "p": float64(0), "c": float64(0), "len": float64(0), @@ -137,9 +137,9 @@ var compileEnvPrototypeV1 = map[string]interface{}{ "_trace": func(int, bool, float64) float64 { return 1 }, "_trace_int": func(int, bool, int) int { return 1 }, "header": func(string) string { return "" }, - "param": func(string) interface{} { return nil }, - "u": func(string) interface{} { return nil }, - "has": func(interface{}, string) bool { return false }, + "param": func(string) any { return nil }, + "u": func(string) any { return nil }, + "has": func(any, string) bool { return false }, "hour": func(string) int { return 0 }, "minute": func(string) int { return 0 }, "weekday": func(string) int { return 0 }, @@ -152,7 +152,7 @@ var compileEnvPrototypeV1 = map[string]interface{}{ "floor": math.Floor, } -func getCompileEnv(version int) map[string]interface{} { +func getCompileEnv(version int) map[string]any { switch version { default: return compileEnvPrototypeV1 diff --git a/pkg/billingexpr/run.go b/pkg/billingexpr/run.go index 0078781ed1..d90cb78cf0 100644 --- a/pkg/billingexpr/run.go +++ b/pkg/billingexpr/run.go @@ -54,7 +54,7 @@ func runProgram(prog *vm.Program, requestRules []RequestRuleTrace, params TokenP } headers := normalizeHeaders(request.Headers) - env := map[string]interface{}{ + env := map[string]any{ "p": params.P, "c": params.C, "len": params.Len, @@ -91,7 +91,7 @@ func runProgram(prog *vm.Program, requestRules []RequestRuleTrace, params TokenP "header": func(key string) string { return headers[strings.ToLower(strings.TrimSpace(key))] }, - "param": func(path string) interface{} { + "param": func(path string) any { path = strings.TrimSpace(path) if path == "" || len(request.Body) == 0 { return nil @@ -102,13 +102,13 @@ func runProgram(prog *vm.Program, requestRules []RequestRuleTrace, params TokenP } return result.Value() }, - "u": func(name string) interface{} { + "u": func(name string) any { if request.Usage == nil { return nil } return request.Usage[strings.TrimSpace(name)] }, - "has": func(source interface{}, substr string) bool { + "has": func(source any, substr string) bool { if source == nil || substr == "" { return false } diff --git a/pkg/jsplugin/engine.go b/pkg/jsplugin/engine.go index 8c3999b8d0..6f1cf22323 100644 --- a/pkg/jsplugin/engine.go +++ b/pkg/jsplugin/engine.go @@ -5,6 +5,7 @@ import ( "errors" "fmt" "regexp" + "slices" "strings" "sync" "time" @@ -137,7 +138,7 @@ func Compile(source string, options Options) (*Engine, error) { return nil, fmt.Errorf("unsupported plugin syntax %q: plugins must be synchronous and cannot import modules", strings.TrimSpace(match)) } - resolve := func(_ interface{}, specifier string) (sobek.ModuleRecord, error) { + resolve := func(_ any, specifier string) (sobek.ModuleRecord, error) { return nil, fmt.Errorf("plugin imports are disabled: %s", specifier) } // Plugin source is untrusted; without this option a sourceMappingURL @@ -446,13 +447,7 @@ func resolveExportPath(instance *runtimeInstance, exportName string, members []s for _, member := range members { hookName += "." + member object := value.ToObject(instance.runtime) - own := false - for _, name := range object.GetOwnPropertyNames() { - if name == member { - own = true - break - } - } + own := slices.Contains(object.GetOwnPropertyNames(), member) if !own { return nil, hookName, false } @@ -500,7 +495,7 @@ func (e *Engine) newRuntime(ctx context.Context) (instance *runtimeInstance, err panic(recovered) } }() - promise := runtime.CyclicModuleRecordEvaluate(e.module, func(_ interface{}, specifier string) (sobek.ModuleRecord, error) { + promise := runtime.CyclicModuleRecordEvaluate(e.module, func(_ any, specifier string) (sobek.ModuleRecord, error) { return nil, fmt.Errorf("plugin imports are disabled: %s", specifier) }) if promise.State() != sobek.PromiseStateFulfilled { diff --git a/pkg/jsplugin/registry.go b/pkg/jsplugin/registry.go index bad9ad58c5..692d2e3f4c 100644 --- a/pkg/jsplugin/registry.go +++ b/pkg/jsplugin/registry.go @@ -1077,7 +1077,7 @@ func normalizeV1Meta(meta *Meta) error { if len(host) > 253 || host == "" { return fmt.Errorf("plugin meta website must have a valid hostname") } - for _, label := range strings.Split(host, ".") { + for label := range strings.SplitSeq(host, ".") { if !websiteHostLabelPattern.MatchString(label) { return fmt.Errorf("plugin meta website must have a valid ASCII hostname; use punycode for internationalized domains") } @@ -1848,9 +1848,7 @@ func validateLocalizedText(text LocalizedText, name string, maxRunes int) error for locale := range text { delete(text, locale) } - for locale, value := range canonical { - text[locale] = value - } + maps.Copy(text, canonical) return nil } diff --git a/pkg/jsplugin/routing.go b/pkg/jsplugin/routing.go index 0e14264bc3..41f42bd818 100644 --- a/pkg/jsplugin/routing.go +++ b/pkg/jsplugin/routing.go @@ -243,9 +243,7 @@ type RouteRequestContext struct { func (r RouteRequestContext) JSValue() map[string]any { params := make(map[string]string, len(r.Params)) - for key, value := range r.Params { - params[key] = value - } + maps.Copy(params, r.Params) query := make(map[string][]string, len(r.Query)) for key, values := range r.Query { query[key] = append([]string(nil), values...) diff --git a/plugins/hailuo_responses_test.go b/plugins/hailuo_responses_test.go index b08af2fcc5..1b8cddfd35 100644 --- a/plugins/hailuo_responses_test.go +++ b/plugins/hailuo_responses_test.go @@ -205,7 +205,7 @@ func TestHailuoH3BuildSubmitRequest(t *testing.T) { func TestHailuoH3RejectsOutOfContractRequests(t *testing.T) { plugin := loadHailuoPlugin(t) tenReferenceImages := make([]any, 0, 10) - for i := 0; i < 10; i++ { + for range 10 { tenReferenceImages = append(tenReferenceImages, map[string]any{ "type": "image_url", "role": "reference_image", "image_url": map[string]any{"url": "u"}, }) @@ -372,7 +372,7 @@ func TestHailuoParseTaskResult(t *testing.T) { func TestHailuoExtractUsageFacts(t *testing.T) { plugin := loadHailuoPlugin(t) nineReferenceImages := make([]any, 0, 9) - for i := 0; i < 9; i++ { + for range 9 { nineReferenceImages = append(nineReferenceImages, map[string]any{ "type": "image_url", "role": "reference_image", "image_url": map[string]any{"url": "image"}, }) diff --git a/relay/channel/ali/dto.go b/relay/channel/ali/dto.go index 58df876176..beaa149a3d 100644 --- a/relay/channel/ali/dto.go +++ b/relay/channel/ali/dto.go @@ -35,8 +35,8 @@ type AliParameters struct { type AliChatRequest struct { Model string `json:"model"` - Input AliInput `json:"input,omitempty"` - Parameters AliParameters `json:"parameters,omitempty"` + Input AliInput `json:"input"` + Parameters AliParameters `json:"parameters"` } type AliEmbeddingRequest struct { @@ -96,7 +96,7 @@ type AliOutput struct { Role string `json:"role,omitempty"` Content []AliMediaContent `json:"content,omitempty"` ReasoningContent string `json:"reasoning_content,omitempty"` - } `json:"message,omitempty"` + } `json:"message"` } `json:"choices,omitempty"` } @@ -166,7 +166,7 @@ type AliResponse struct { type AliImageRequest struct { Model string `json:"model"` Input any `json:"input"` - Parameters AliImageParameters `json:"parameters,omitempty"` + Parameters AliImageParameters `json:"parameters"` ResponseFormat string `json:"response_format,omitempty"` } @@ -223,7 +223,7 @@ type AliRerankInput struct { type AliRerankRequest struct { Model string `json:"model"` Input AliRerankInput `json:"input"` - Parameters AliRerankParameters `json:"parameters,omitempty"` + Parameters AliRerankParameters `json:"parameters"` } type AliRerankResponse struct { diff --git a/relay/channel/api_request_getbody_test.go b/relay/channel/api_request_getbody_test.go index 9a2de73337..c115e85325 100644 --- a/relay/channel/api_request_getbody_test.go +++ b/relay/channel/api_request_getbody_test.go @@ -56,7 +56,7 @@ func TestApplyUpstreamBodyMetadataSetsReplayableMetadata(t *testing.T) { require.NoError(t, err) assert.Equal(t, payload, sent) - for i := 0; i < 2; i++ { + for i := range 2 { rc, err := req.GetBody() require.NoError(t, err) replay, err := io.ReadAll(rc) @@ -110,7 +110,6 @@ func TestApplyUpstreamBodyMetadataKeepsNativeMetadataForNonReplayableBody(t *tes } for _, test := range tests { - test := test t.Run(test.name, func(t *testing.T) { t.Parallel() @@ -241,7 +240,7 @@ func TestDoTaskApiRequest_KeepsReplayableGetBody(t *testing.T) { require.NotNil(t, req.GetBody) // Even after the request body has been fully written, GetBody must still // return the complete payload, repeatedly. - for i := 0; i < 2; i++ { + for i := range 2 { rc, err := req.GetBody() require.NoError(t, err) replay, err := io.ReadAll(rc) @@ -400,7 +399,7 @@ func runGoAwayAfterFirstRequestServer(ln net.Listener) <-chan h2ServerResult { res := h2ServerResult{} defer func() { resCh <- res }() - for attempt := 0; attempt < 2; attempt++ { + for attempt := range 2 { conn, framer, err := acceptH2TestConnection(ln) if err != nil { res.err = err diff --git a/relay/channel/aws/dto.go b/relay/channel/aws/dto.go index 359d2001fb..09ec3c063f 100644 --- a/relay/channel/aws/dto.go +++ b/relay/channel/aws/dto.go @@ -133,7 +133,7 @@ func parseStopSequences(stop any) []string { } case []string: return v - case []interface{}: + case []any: var sequences []string for _, item := range v { if str, ok := item.(string); ok && str != "" { diff --git a/relay/channel/aws/relay-aws.go b/relay/channel/aws/relay-aws.go index c4751b5af8..25246e1754 100644 --- a/relay/channel/aws/relay-aws.go +++ b/relay/channel/aws/relay-aws.go @@ -186,7 +186,7 @@ func buildAwsRequestBody(c *gin.Context, info *relaycommon.RelayInfo, awsClaudeR if err != nil { return nil, errors.Wrap(err, "get request body bytes fail") } - var data map[string]interface{} + var data map[string]any if err := common.Unmarshal(body, &data); err != nil { return nil, errors.Wrap(err, "pass-through unmarshal request body fail") } diff --git a/relay/channel/claude/relay_claude_test.go b/relay/channel/claude/relay_claude_test.go index 937d7998b5..8b7c4d0d00 100644 --- a/relay/channel/claude/relay_claude_test.go +++ b/relay/channel/claude/relay_claude_test.go @@ -23,14 +23,14 @@ func TestResponseOpenAI2ClaudeToolUseInputIsObject(t *testing.T) { tests := []struct { name string args string - want map[string]interface{} + want map[string]any }{ - {name: "object", args: `{"q":"x"}`, want: map[string]interface{}{"q": "x"}}, - {name: "empty", args: "", want: map[string]interface{}{}}, - {name: "invalid", args: "{", want: map[string]interface{}{}}, - {name: "null", args: "null", want: map[string]interface{}{}}, - {name: "array", args: `["x"]`, want: map[string]interface{}{}}, - {name: "string", args: `"x"`, want: map[string]interface{}{}}, + {name: "object", args: `{"q":"x"}`, want: map[string]any{"q": "x"}}, + {name: "empty", args: "", want: map[string]any{}}, + {name: "invalid", args: "{", want: map[string]any{}}, + {name: "null", args: "null", want: map[string]any{}}, + {name: "array", args: `["x"]`, want: map[string]any{}}, + {name: "string", args: `"x"`, want: map[string]any{}}, } for _, tt := range tests { diff --git a/relay/channel/gemini/adaptor.go b/relay/channel/gemini/adaptor.go index 073e501526..e817896b19 100644 --- a/relay/channel/gemini/adaptor.go +++ b/relay/channel/gemini/adaptor.go @@ -195,9 +195,9 @@ func (a *Adaptor) ConvertEmbeddingRequest(c *gin.Context, info *relaycommon.Rela // batch endpoint upstream to avoid payload/endpoint mismatches. info.IsGeminiBatchEmbedding = true // process all inputs - geminiRequests := make([]map[string]interface{}, 0, len(inputs)) + geminiRequests := make([]map[string]any, 0, len(inputs)) for _, input := range inputs { - geminiRequest := map[string]interface{}{ + geminiRequest := map[string]any{ "model": fmt.Sprintf("models/%s", info.UpstreamModelName), "content": dto.GeminiChatContent{ Parts: []dto.GeminiPart{ @@ -221,7 +221,7 @@ func (a *Adaptor) ConvertEmbeddingRequest(c *gin.Context, info *relaycommon.Rela geminiRequests = append(geminiRequests, geminiRequest) } - return map[string]interface{}{ + return map[string]any{ "requests": geminiRequests, }, nil } diff --git a/relay/channel/gemini/adaptor_responses_test.go b/relay/channel/gemini/adaptor_responses_test.go index fb0888d828..481dd2edbb 100644 --- a/relay/channel/gemini/adaptor_responses_test.go +++ b/relay/channel/gemini/adaptor_responses_test.go @@ -93,14 +93,14 @@ func TestConvertOpenAIResponsesRequestToGeminiFunctionCallConversation(t *testin require.Len(t, got.Contents[0].Parts, 2) require.NotNil(t, got.Contents[0].Parts[0].FunctionCall) assert.Equal(t, "lookup", got.Contents[0].Parts[0].FunctionCall.FunctionName) - assert.Equal(t, map[string]interface{}{"q": "x"}, got.Contents[0].Parts[0].FunctionCall.Arguments) + assert.Equal(t, map[string]any{"q": "x"}, got.Contents[0].Parts[0].FunctionCall.Arguments) assert.Equal(t, "I will call.", got.Contents[0].Parts[1].Text) assert.Equal(t, "user", got.Contents[1].Role) require.Len(t, got.Contents[1].Parts, 1) require.NotNil(t, got.Contents[1].Parts[0].FunctionResponse) assert.Equal(t, "lookup", got.Contents[1].Parts[0].FunctionResponse.Name) - assert.Equal(t, map[string]interface{}{"ok": true}, got.Contents[1].Parts[0].FunctionResponse.Response) + assert.Equal(t, map[string]any{"ok": true}, got.Contents[1].Parts[0].FunctionResponse.Response) } func TestConvertOpenAIResponsesRequestToGeminiSkipsCustomToolCalls(t *testing.T) { diff --git a/relay/channel/gemini/relay-gemini.go b/relay/channel/gemini/relay-gemini.go index 81b4542257..494888a63c 100644 --- a/relay/channel/gemini/relay-gemini.go +++ b/relay/channel/gemini/relay-gemini.go @@ -552,7 +552,7 @@ func FetchGeminiModels(baseURL, apiKey, proxyURL string) ([]string, error) { nextPageToken := "" maxPages := 100 // Safety limit to prevent infinite loops - for page := 0; page < maxPages; page++ { + for range maxPages { url := fmt.Sprintf("%s/v1beta/models", baseURL) if nextPageToken != "" { url = fmt.Sprintf("%s?pageToken=%s", url, nextPageToken) diff --git a/relay/channel/gemini/relay_gemini_usage_test.go b/relay/channel/gemini/relay_gemini_usage_test.go index 1fd9f1c3a0..fe284597e9 100644 --- a/relay/channel/gemini/relay_gemini_usage_test.go +++ b/relay/channel/gemini/relay_gemini_usage_test.go @@ -104,7 +104,7 @@ func TestGeminiChatStreamHandlerClaudeFirstFrameUsesUpstreamUsage(t *testing.T) require.Equal(t, 3868, usage.PromptTokens) var startUsage, deltaUsage *dto.ClaudeUsage - for _, line := range strings.Split(recorder.Body.String(), "\n") { + for line := range strings.SplitSeq(recorder.Body.String(), "\n") { payload, ok := strings.CutPrefix(strings.TrimSpace(line), "data: ") if !ok { continue diff --git a/relay/channel/ollama/dto.go b/relay/channel/ollama/dto.go index 80e1ecfbc9..d9213e8d3c 100644 --- a/relay/channel/ollama/dto.go +++ b/relay/channel/ollama/dto.go @@ -15,9 +15,9 @@ type OllamaChatMessage struct { } type OllamaToolFunction struct { - Name string `json:"name"` - Description string `json:"description,omitempty"` - Parameters interface{} `json:"parameters,omitempty"` + Name string `json:"name"` + Description string `json:"description,omitempty"` + Parameters any `json:"parameters,omitempty"` } type OllamaTool struct { @@ -28,19 +28,19 @@ type OllamaTool struct { type OllamaToolCall struct { ID string `json:"id,omitempty"` Function struct { - Name string `json:"name"` - Arguments interface{} `json:"arguments"` + Name string `json:"name"` + Arguments any `json:"arguments"` } `json:"function"` } type OllamaChatRequest struct { Model string `json:"model"` Messages []OllamaChatMessage `json:"messages"` - Tools interface{} `json:"tools,omitempty"` - Format interface{} `json:"format,omitempty"` + Tools any `json:"tools,omitempty"` + Format any `json:"format,omitempty"` Stream bool `json:"stream"` Options map[string]any `json:"options,omitempty"` - KeepAlive interface{} `json:"keep_alive,omitempty"` + KeepAlive any `json:"keep_alive,omitempty"` Think json.RawMessage `json:"think,omitempty"` } @@ -49,16 +49,16 @@ type OllamaGenerateRequest struct { Prompt string `json:"prompt,omitempty"` Suffix string `json:"suffix,omitempty"` Images []string `json:"images,omitempty"` - Format interface{} `json:"format,omitempty"` + Format any `json:"format,omitempty"` Stream bool `json:"stream"` Options map[string]any `json:"options,omitempty"` - KeepAlive interface{} `json:"keep_alive,omitempty"` + KeepAlive any `json:"keep_alive,omitempty"` Think json.RawMessage `json:"think,omitempty"` } type OllamaEmbeddingRequest struct { Model string `json:"model"` - Input interface{} `json:"input"` + Input any `json:"input"` Options map[string]any `json:"options,omitempty"` Dimensions int `json:"dimensions,omitempty"` } @@ -79,7 +79,7 @@ type OllamaModel struct { Size int64 `json:"size"` Digest string `json:"digest,omitempty"` ModifiedAt string `json:"modified_at"` - Details OllamaModelDetail `json:"details,omitempty"` + Details OllamaModelDetail `json:"details"` } type OllamaModelDetail struct { diff --git a/relay/channel/ollama/relay-ollama.go b/relay/channel/ollama/relay-ollama.go index e517a1e6aa..95643ddc64 100644 --- a/relay/channel/ollama/relay-ollama.go +++ b/relay/channel/ollama/relay-ollama.go @@ -181,7 +181,7 @@ func openAIChatToOllamaChat(c *gin.Context, r *dto.GeneralOpenAIRequest) (*Ollam if len(parsed) > 0 { calls := make([]OllamaToolCall, 0, len(parsed)) for _, tc := range parsed { - var args interface{} + var args any if tc.Function.Arguments != "" { _ = common.Unmarshal([]byte(tc.Function.Arguments), &args) } diff --git a/relay/channel/openai/adaptor.go b/relay/channel/openai/adaptor.go index cafe1fd705..cf9aaf1b43 100644 --- a/relay/channel/openai/adaptor.go +++ b/relay/channel/openai/adaptor.go @@ -105,12 +105,12 @@ func (a *Adaptor) Init(info *relaycommon.RelayInfo) { func (a *Adaptor) GetRequestURL(info *relaycommon.RelayInfo) (string, error) { if info.RelayMode == relayconstant.RelayModeRealtime { - if strings.HasPrefix(info.ChannelBaseUrl, "https://") { - baseUrl := strings.TrimPrefix(info.ChannelBaseUrl, "https://") + if after, ok := strings.CutPrefix(info.ChannelBaseUrl, "https://"); ok { + baseUrl := after baseUrl = "wss://" + baseUrl info.ChannelBaseUrl = baseUrl - } else if strings.HasPrefix(info.ChannelBaseUrl, "http://") { - baseUrl := strings.TrimPrefix(info.ChannelBaseUrl, "http://") + } else if after, ok := strings.CutPrefix(info.ChannelBaseUrl, "http://"); ok { + baseUrl := after baseUrl = "ws://" + baseUrl info.ChannelBaseUrl = baseUrl } diff --git a/relay/channel/openai/chat_via_responses_test.go b/relay/channel/openai/chat_via_responses_test.go index 27ee71c9ab..8384c355ca 100644 --- a/relay/channel/openai/chat_via_responses_test.go +++ b/relay/channel/openai/chat_via_responses_test.go @@ -123,7 +123,7 @@ func TestOaiResponsesToChatStreamHandlerConvertsClaudeSSETerminalsAndUsage(t *te assert.Equal(t, 1, strings.Count(got, "event: message_stop\n")) messageDeltaFrame := "" - for _, frame := range strings.Split(got, "\n\n") { + for frame := range strings.SplitSeq(got, "\n\n") { if strings.HasPrefix(frame, "event: message_delta\n") { messageDeltaFrame = frame break diff --git a/relay/channel/openai/relay-openai.go b/relay/channel/openai/relay-openai.go index 285e342f82..edcaee35b9 100644 --- a/relay/channel/openai/relay-openai.go +++ b/relay/channel/openai/relay-openai.go @@ -313,7 +313,7 @@ func OpenaiHandler(c *gin.Context, info *relaycommon.RelayInfo, resp *http.Respo switch info.RelayFormat { case types.RelayFormatOpenAI: if usageModified { - var bodyMap map[string]interface{} + var bodyMap map[string]any err = common.Unmarshal(responseBody, &bodyMap) if err != nil { return nil, types.NewOpenAIError(err, types.ErrorCodeBadResponseBody, http.StatusInternalServerError) diff --git a/relay/channel/openai/relay_image.go b/relay/channel/openai/relay_image.go index 1e6be0dd4c..b330e7611b 100644 --- a/relay/channel/openai/relay_image.go +++ b/relay/channel/openai/relay_image.go @@ -275,7 +275,7 @@ func openaiImageJSONAsStreamHandler(c *gin.Context, info *relaycommon.RelayInfo, } } - for i := int64(0); i < imageCount; i++ { + for i := range imageCount { image := gjson.GetBytes(responseBody, "data."+strconv.FormatInt(i, 10)) payload := []byte(`{"type":"image_generation.completed"}`) payload, err = sjson.SetBytes(payload, "created_at", created) diff --git a/relay/channel/task/jsplugin/adaptor.go b/relay/channel/task/jsplugin/adaptor.go index 6b150cac0b..0adabc1242 100644 --- a/relay/channel/task/jsplugin/adaptor.go +++ b/relay/channel/task/jsplugin/adaptor.go @@ -1198,9 +1198,7 @@ func (a *TaskAdaptor) submitContext(c *gin.Context, info *relaycommon.RelayInfo) if a.routeRequest != nil { routeRequest = *a.routeRequest requestHeaders = make(map[string]string, len(a.requestHeaders)) - for name, value := range a.requestHeaders { - requestHeaders[name] = value - } + maps.Copy(requestHeaders, a.requestHeaders) files = append(files, a.files...) } if c != nil { diff --git a/relay/channel/tencent/dto.go b/relay/channel/tencent/dto.go index 65c548a964..102a879d00 100644 --- a/relay/channel/tencent/dto.go +++ b/relay/channel/tencent/dto.go @@ -56,20 +56,20 @@ type TencentUsage struct { type TencentResponseChoices struct { FinishReason string `json:"FinishReason,omitempty"` // 流式结束标志位,为 stop 则表示尾包 - Messages TencentMessage `json:"Message,omitempty"` // 内容,同步模式返回内容,流模式为 null 输出 content 内容总数最多支持 1024token。 - Delta TencentMessage `json:"Delta,omitempty"` // 内容,流模式返回内容,同步模式为 null 输出 content 内容总数最多支持 1024token。 + Messages TencentMessage `json:"Message"` // 内容,同步模式返回内容,流模式为 null 输出 content 内容总数最多支持 1024token。 + Delta TencentMessage `json:"Delta"` // 内容,流模式返回内容,同步模式为 null 输出 content 内容总数最多支持 1024token。 } type TencentChatResponse struct { Choices []TencentResponseChoices `json:"Choices,omitempty"` // 结果 Created int64 `json:"Created,omitempty"` // unix 时间戳的字符串 Id string `json:"Id,omitempty"` // 会话 id - Usage TencentUsage `json:"Usage,omitempty"` // token 数量 - Error TencentError `json:"Error,omitempty"` // 错误信息 注意:此字段可能返回 null,表示取不到有效值 + Usage TencentUsage `json:"Usage"` // token 数量 + Error TencentError `json:"Error"` // 错误信息 注意:此字段可能返回 null,表示取不到有效值 Note string `json:"Note,omitempty"` // 注释 ReqID string `json:"Req_id,omitempty"` // 唯一请求 Id,每次请求都会返回。用于反馈接口入参 } type TencentChatResponseSB struct { - Response TencentChatResponse `json:"Response,omitempty"` + Response TencentChatResponse `json:"Response"` } diff --git a/relay/channel/tencent/relay-tencent.go b/relay/channel/tencent/relay-tencent.go index 611c186def..01b1108843 100644 --- a/relay/channel/tencent/relay-tencent.go +++ b/relay/channel/tencent/relay-tencent.go @@ -91,7 +91,7 @@ func streamResponseTencent2OpenAI(TencentResponse *TencentChatResponse) *dto.Cha } func tencentStreamHandler(c *gin.Context, info *relaycommon.RelayInfo, resp *http.Response) (*dto.Usage, *types.NewAPIError) { - var responseText string + var responseText strings.Builder scanner := helper.NewStreamScanner(resp.Body) scanner.Split(bufio.ScanLines) @@ -113,7 +113,7 @@ func tencentStreamHandler(c *gin.Context, info *relaycommon.RelayInfo, resp *htt response := streamResponseTencent2OpenAI(&tencentResponse) if len(response.Choices) != 0 { - responseText += response.Choices[0].Delta.GetContentString() + responseText.WriteString(response.Choices[0].Delta.GetContentString()) } err = helper.ObjectData(c, response) @@ -130,7 +130,7 @@ func tencentStreamHandler(c *gin.Context, info *relaycommon.RelayInfo, resp *htt service.CloseResponseBodyGracefully(resp) - return service.ResponseText2Usage(c, responseText, info.UpstreamModelName, info.GetEstimatePromptTokens()), nil + return service.ResponseText2Usage(c, responseText.String(), info.UpstreamModelName, info.GetEstimatePromptTokens()), nil } func tencentHandler(c *gin.Context, info *relaycommon.RelayInfo, resp *http.Response) (*dto.Usage, *types.NewAPIError) { diff --git a/relay/common/outbound_body_test.go b/relay/common/outbound_body_test.go index 28c3aa699c..04535b4000 100644 --- a/relay/common/outbound_body_test.go +++ b/relay/common/outbound_body_test.go @@ -27,7 +27,7 @@ func TestNewOutboundJSONBody_GetBodyReplaysFullBody(t *testing.T) { // GetBody must hand out the complete body again — and repeatedly, since the // transport may need more than one retry. - for i := 0; i < 2; i++ { + for i := range 2 { rc, err := body.NewReader() require.NoError(t, err) replay, err := io.ReadAll(rc) diff --git a/relay/common/override.go b/relay/common/override.go index 477af24677..b87fe24a91 100644 --- a/relay/common/override.go +++ b/relay/common/override.go @@ -3,8 +3,10 @@ package common import ( "errors" "fmt" + "maps" "net/http" "regexp" + "slices" "sort" "strconv" "strings" @@ -53,17 +55,17 @@ type paramOverrideAuditRecorder struct { } type ConditionOperation struct { - Path string `json:"path"` // JSON路径 - Mode string `json:"mode"` // full, prefix, suffix, contains, gt, gte, lt, lte - Value interface{} `json:"value"` // 匹配的值 - Invert bool `json:"invert"` // 反选功能,true表示取反结果 - PassMissingKey bool `json:"pass_missing_key"` // 未获取到json key时的行为 + Path string `json:"path"` // JSON路径 + Mode string `json:"mode"` // full, prefix, suffix, contains, gt, gte, lt, lte + Value any `json:"value"` // 匹配的值 + Invert bool `json:"invert"` // 反选功能,true表示取反结果 + PassMissingKey bool `json:"pass_missing_key"` // 未获取到json key时的行为 } type ParamOperation struct { Path string `json:"path"` Mode string `json:"mode"` // delete, set, move, copy, prepend, append, trim_prefix, trim_suffix, ensure_prefix, ensure_suffix, trim_space, to_lower, to_upper, replace, regex_replace, return_error, prune_objects, set_header, delete_header, copy_header, move_header, pass_headers, sync_fields - Value interface{} `json:"value"` + Value any `json:"value"` KeepOrigin bool `json:"keep_origin"` From string `json:"from,omitempty"` To string `json:"to,omitempty"` @@ -141,7 +143,7 @@ func NewAPIErrorFromParamOverride(err *ParamOverrideReturnError) *types.NewAPIEr }, statusCode, opts...) } -func ApplyParamOverride(jsonData []byte, paramOverride map[string]interface{}, conditionContext map[string]interface{}) ([]byte, error) { +func ApplyParamOverride(jsonData []byte, paramOverride map[string]any, conditionContext map[string]any) ([]byte, error) { if len(paramOverride) == 0 { return jsonData, nil } @@ -167,11 +169,11 @@ func ApplyParamOverride(jsonData []byte, paramOverride map[string]interface{}, c return applyOperationsLegacy(jsonData, paramOverride, auditRecorder) } -func buildLegacyParamOverride(paramOverride map[string]interface{}) map[string]interface{} { +func buildLegacyParamOverride(paramOverride map[string]any) map[string]any { if len(paramOverride) == 0 { return nil } - legacy := make(map[string]interface{}, len(paramOverride)) + legacy := make(map[string]any, len(paramOverride)) for key, value := range paramOverride { if strings.EqualFold(strings.TrimSpace(key), "operations") { continue @@ -324,7 +326,7 @@ func reasoningEffortFromBudgetValue(value gjson.Result) (string, bool) { } } -func shouldEnableParamOverrideAudit(paramOverride map[string]interface{}) bool { +func shouldEnableParamOverrideAudit(paramOverride map[string]any) bool { if common.DebugEnabled { return true } @@ -354,7 +356,7 @@ func shouldEnableParamOverrideAudit(paramOverride map[string]interface{}) bool { return false } -func getParamOverrideAuditRecorder(context map[string]interface{}) *paramOverrideAuditRecorder { +func getParamOverrideAuditRecorder(context map[string]any) *paramOverrideAuditRecorder { if context == nil { return nil } @@ -362,7 +364,7 @@ func getParamOverrideAuditRecorder(context map[string]interface{}) *paramOverrid return recorder } -func (r *paramOverrideAuditRecorder) recordOperation(mode, path, from, to string, value interface{}) { +func (r *paramOverrideAuditRecorder) recordOperation(mode, path, from, to string, value any) { if r == nil { return } @@ -396,15 +398,10 @@ func shouldAuditOperation(mode, path, from, to string) bool { if common.DebugEnabled { return true } - for _, candidate := range []string{path, from, to} { - if shouldAuditParamPath(candidate) { - return true - } - } - return false + return slices.ContainsFunc([]string{path, from, to}, shouldAuditParamPath) } -func formatParamOverrideAuditValue(value interface{}) string { +func formatParamOverrideAuditValue(value any) string { switch typed := value.(type) { case nil: return "" @@ -415,7 +412,7 @@ func formatParamOverrideAuditValue(value interface{}) string { } } -func buildParamOverrideAuditLine(mode, path, from, to string, value interface{}) string { +func buildParamOverrideAuditLine(mode, path, from, to string, value any) string { mode = strings.TrimSpace(mode) path = strings.TrimSpace(path) from = strings.TrimSpace(from) @@ -503,25 +500,25 @@ func buildParamOverrideAuditLine(mode, path, from, to string, value interface{}) } } -func getParamOverrideMap(info *RelayInfo) map[string]interface{} { +func getParamOverrideMap(info *RelayInfo) map[string]any { if info == nil || info.ChannelMeta == nil { return nil } return info.ChannelMeta.ParamOverride } -func getHeaderOverrideMap(info *RelayInfo) map[string]interface{} { +func getHeaderOverrideMap(info *RelayInfo) map[string]any { if info == nil || info.ChannelMeta == nil { return nil } return info.ChannelMeta.HeadersOverride } -func sanitizeHeaderOverrideMap(source map[string]interface{}) map[string]interface{} { +func sanitizeHeaderOverrideMap(source map[string]any) map[string]any { if len(source) == 0 { - return map[string]interface{}{} + return map[string]any{} } - target := make(map[string]interface{}, len(source)) + target := make(map[string]any, len(source)) for key, value := range source { normalizedKey := normalizeHeaderContextKey(key) if normalizedKey == "" { @@ -550,9 +547,9 @@ func isHeaderPassthroughRuleKeyForOverride(key string) bool { return strings.HasPrefix(key, "re:") || strings.HasPrefix(key, "regex:") } -func GetEffectiveHeaderOverride(info *RelayInfo) map[string]interface{} { +func GetEffectiveHeaderOverride(info *RelayInfo) map[string]any { if info == nil { - return map[string]interface{}{} + return map[string]any{} } if info.UseRuntimeHeadersOverride { return sanitizeHeaderOverrideMap(info.RuntimeHeadersOverride) @@ -560,25 +557,25 @@ func GetEffectiveHeaderOverride(info *RelayInfo) map[string]interface{} { return sanitizeHeaderOverrideMap(getHeaderOverrideMap(info)) } -func tryParseOperations(paramOverride map[string]interface{}) ([]ParamOperation, bool) { +func tryParseOperations(paramOverride map[string]any) ([]ParamOperation, bool) { // 检查是否包含 "operations" 字段 opsValue, exists := paramOverride["operations"] if !exists { return nil, false } - var opMaps []map[string]interface{} + var opMaps []map[string]any switch ops := opsValue.(type) { - case []interface{}: - opMaps = make([]map[string]interface{}, 0, len(ops)) + case []any: + opMaps = make([]map[string]any, 0, len(ops)) for _, op := range ops { - opMap, ok := op.(map[string]interface{}) + opMap, ok := op.(map[string]any) if !ok { return nil, false } opMaps = append(opMaps, opMap) } - case []map[string]interface{}: + case []map[string]any: opMaps = ops default: return nil, false @@ -799,7 +796,7 @@ func compareNumeric(jsonValue, targetValue gjson.Result, operator string) (bool, // 语义保持:每个 paramOverride 顶层 key 视为字面 key(不解析点号路径), // 与旧的 reqMap[key] = value 一致。包含 `.` `*` `?` `\` 的 key 会被转义, // 防止被 sjson 当作嵌套路径或通配符。 -func applyOperationsLegacy(jsonData []byte, paramOverride map[string]interface{}, auditRecorder *paramOverrideAuditRecorder) ([]byte, error) { +func applyOperationsLegacy(jsonData []byte, paramOverride map[string]any, auditRecorder *paramOverrideAuditRecorder) ([]byte, error) { if len(paramOverride) == 0 { return jsonData, nil } @@ -844,7 +841,7 @@ func escapeSjsonLiteralKey(key string) string { // payload 来说每次重试都额外多花 2 倍 body 体积的临时内存。 // 这里改成全程在 []byte 上工作,sjson.SetBytes / gjson.GetBytes 都是 // 直接读写 []byte,每个操作只会产生一份新 buffer。 -func applyOperations(jsonData []byte, operations []ParamOperation, conditionContext map[string]interface{}) ([]byte, error) { +func applyOperations(jsonData []byte, operations []ParamOperation, conditionContext map[string]any) ([]byte, error) { context := ensureContextMap(conditionContext) auditRecorder := getParamOverrideAuditRecorder(context) contextJSON, err := marshalContextJSON(context) @@ -1094,7 +1091,7 @@ func applyOperations(jsonData []byte, operations []ParamOperation, conditionCont return result, nil } -func parseParamOverrideReturnError(value interface{}) (*ParamOverrideReturnError, error) { +func parseParamOverrideReturnError(value any) (*ParamOverrideReturnError, error) { result := &ParamOverrideReturnError{ StatusCode: http.StatusBadRequest, Code: string(types.ErrorCodeInvalidRequest), @@ -1107,7 +1104,7 @@ func parseParamOverrideReturnError(value interface{}) (*ParamOverrideReturnError return nil, fmt.Errorf("return_error value is required") case string: result.Message = strings.TrimSpace(raw) - case map[string]interface{}: + case map[string]any: if message, ok := raw["message"].(string); ok { result.Message = strings.TrimSpace(message) } @@ -1160,7 +1157,7 @@ func parseParamOverrideReturnError(value interface{}) (*ParamOverrideReturnError return result, nil } -func parseOverrideInt(v interface{}) (int, bool) { +func parseOverrideInt(v any) (int, bool) { switch value := v.(type) { case int: return value, true @@ -1174,14 +1171,14 @@ func parseOverrideInt(v interface{}) (int, bool) { } } -func ensureContextMap(conditionContext map[string]interface{}) map[string]interface{} { +func ensureContextMap(conditionContext map[string]any) map[string]any { if conditionContext != nil { return conditionContext } - return make(map[string]interface{}) + return make(map[string]any) } -func marshalContextJSON(context map[string]interface{}) (string, error) { +func marshalContextJSON(context map[string]any) (string, error) { if context == nil || len(context) == 0 { return "", nil } @@ -1192,7 +1189,7 @@ func marshalContextJSON(context map[string]interface{}) (string, error) { return string(ctxBytes), nil } -func setHeaderOverrideInContext(context map[string]interface{}, headerName string, value interface{}, keepOrigin bool) error { +func setHeaderOverrideInContext(context map[string]any, headerName string, value any, keepOrigin bool) error { headerName = normalizeHeaderContextKey(headerName) if headerName == "" { return fmt.Errorf("header name is required") @@ -1221,16 +1218,16 @@ func setHeaderOverrideInContext(context map[string]interface{}, headerName strin return nil } -func resolveHeaderOverrideValue(context map[string]interface{}, headerName string, value interface{}) (string, bool, error) { +func resolveHeaderOverrideValue(context map[string]any, headerName string, value any) (string, bool, error) { if value == nil { return "", false, fmt.Errorf("header value is required") } - if mapping, ok := value.(map[string]interface{}); ok { + if mapping, ok := value.(map[string]any); ok { return resolveHeaderOverrideValueByMapping(context, headerName, mapping) } if mapping, ok := value.(map[string]string); ok { - converted := make(map[string]interface{}, len(mapping)) + converted := make(map[string]any, len(mapping)) for key, item := range mapping { converted[key] = item } @@ -1244,7 +1241,7 @@ func resolveHeaderOverrideValue(context map[string]interface{}, headerName strin return headerValue, true, nil } -func resolveHeaderOverrideValueByMapping(context map[string]interface{}, headerName string, mapping map[string]interface{}) (string, bool, error) { +func resolveHeaderOverrideValueByMapping(context map[string]any, headerName string, mapping map[string]any) (string, bool, error) { if len(mapping) == 0 { return "", false, fmt.Errorf("header value mapping cannot be empty") } @@ -1291,7 +1288,7 @@ func resolveHeaderOverrideValueByMapping(context map[string]interface{}, headerN return strings.Join(resultTokens, ","), true, nil } -func parseHeaderAppendTokens(mapping map[string]interface{}) ([]string, error) { +func parseHeaderAppendTokens(mapping map[string]any) ([]string, error) { appendRaw, ok := mapping["$append"] if !ok { return nil, nil @@ -1299,7 +1296,7 @@ func parseHeaderAppendTokens(mapping map[string]interface{}) ([]string, error) { return parseHeaderReplacementTokens(appendRaw) } -func parseHeaderKeepOnlyDeclared(mapping map[string]interface{}) bool { +func parseHeaderKeepOnlyDeclared(mapping map[string]any) bool { keepOnlyDeclaredRaw, ok := mapping["$keep_only_declared"] if !ok { return false @@ -1311,7 +1308,7 @@ func parseHeaderKeepOnlyDeclared(mapping map[string]interface{}) bool { return keepOnlyDeclared } -func parseHeaderReplacementTokens(value interface{}) ([]string, error) { +func parseHeaderReplacementTokens(value any) ([]string, error) { switch raw := value.(type) { case nil: return nil, nil @@ -1323,7 +1320,7 @@ func parseHeaderReplacementTokens(value interface{}) ([]string, error) { tokens = append(tokens, splitHeaderListValue(item)...) } return lo.Uniq(tokens), nil - case []interface{}: + case []any: tokens := make([]string, 0, len(raw)) for _, item := range raw { itemTokens, err := parseHeaderReplacementTokens(item) @@ -1333,7 +1330,7 @@ func parseHeaderReplacementTokens(value interface{}) ([]string, error) { tokens = append(tokens, itemTokens...) } return lo.Uniq(tokens), nil - case map[string]interface{}, map[string]string: + case map[string]any, map[string]string: return nil, fmt.Errorf("header replacement value must be string, array or null") default: token := strings.TrimSpace(fmt.Sprintf("%v", raw)) @@ -1355,7 +1352,7 @@ func splitHeaderListValue(raw string) []string { }) } -func copyHeaderInContext(context map[string]interface{}, fromHeader, toHeader string, keepOrigin bool) error { +func copyHeaderInContext(context map[string]any, fromHeader, toHeader string, keepOrigin bool) error { fromHeader = normalizeHeaderContextKey(fromHeader) toHeader = normalizeHeaderContextKey(toHeader) if fromHeader == "" || toHeader == "" { @@ -1368,7 +1365,7 @@ func copyHeaderInContext(context map[string]interface{}, fromHeader, toHeader st return setHeaderOverrideInContext(context, toHeader, value, keepOrigin) } -func moveHeaderInContext(context map[string]interface{}, fromHeader, toHeader string, keepOrigin bool) error { +func moveHeaderInContext(context map[string]any, fromHeader, toHeader string, keepOrigin bool) error { fromHeader = normalizeHeaderContextKey(fromHeader) toHeader = normalizeHeaderContextKey(toHeader) if fromHeader == "" || toHeader == "" { @@ -1383,7 +1380,7 @@ func moveHeaderInContext(context map[string]interface{}, fromHeader, toHeader st return deleteHeaderOverrideInContext(context, fromHeader) } -func deleteHeaderOverrideInContext(context map[string]interface{}, headerName string) error { +func deleteHeaderOverrideInContext(context map[string]any, headerName string) error { headerName = normalizeHeaderContextKey(headerName) if headerName == "" { return fmt.Errorf("header name is required") @@ -1393,7 +1390,7 @@ func deleteHeaderOverrideInContext(context map[string]interface{}, headerName st return nil } -func parseHeaderPassThroughNames(value interface{}) ([]string, error) { +func parseHeaderPassThroughNames(value any) ([]string, error) { normalizeNames := func(values []string) []string { names := lo.FilterMap(values, func(item string, _ int) (string, bool) { headerName := normalizeHeaderContextKey(item) @@ -1414,7 +1411,7 @@ func parseHeaderPassThroughNames(value interface{}) ([]string, error) { return nil, fmt.Errorf("pass_headers value is required") } if strings.HasPrefix(trimmed, "[") || strings.HasPrefix(trimmed, "{") { - var parsed interface{} + var parsed any if err := common.UnmarshalJsonStr(trimmed, &parsed); err == nil { return parseHeaderPassThroughNames(parsed) } @@ -1424,8 +1421,8 @@ func parseHeaderPassThroughNames(value interface{}) ([]string, error) { return nil, fmt.Errorf("pass_headers value is invalid") } return names, nil - case []interface{}: - names := lo.FilterMap(raw, func(item interface{}, _ int) (string, bool) { + case []any: + names := lo.FilterMap(raw, func(item any, _ int) (string, bool) { headerName := normalizeHeaderContextKey(fmt.Sprintf("%v", item)) if headerName == "" { return "", false @@ -1450,7 +1447,7 @@ func parseHeaderPassThroughNames(value interface{}) ([]string, error) { return nil, fmt.Errorf("pass_headers value is invalid") } return names, nil - case map[string]interface{}: + case map[string]any: candidates := make([]string, 0, 8) if headersRaw, ok := raw["headers"]; ok { names, err := parseHeaderPassThroughNames(headersRaw) @@ -1491,8 +1488,8 @@ func parseSyncTarget(spec string) (syncTarget, error) { return syncTarget{}, fmt.Errorf("sync_fields target is required") } - idx := strings.Index(raw, ":") - if idx < 0 { + before, after, ok := strings.Cut(raw, ":") + if !ok { // Backward compatibility: treat bare value as JSON path. return syncTarget{ kind: "json", @@ -1500,8 +1497,8 @@ func parseSyncTarget(spec string) (syncTarget, error) { }, nil } - kind := strings.ToLower(strings.TrimSpace(raw[:idx])) - key := strings.TrimSpace(raw[idx+1:]) + kind := strings.ToLower(strings.TrimSpace(before)) + key := strings.TrimSpace(after) if key == "" { return syncTarget{}, fmt.Errorf("sync_fields target key is required: %s", raw) } @@ -1522,7 +1519,7 @@ func parseSyncTarget(spec string) (syncTarget, error) { } } -func readSyncTargetValue(data []byte, context map[string]interface{}, target syncTarget) (interface{}, bool, error) { +func readSyncTargetValue(data []byte, context map[string]any, target syncTarget) (any, bool, error) { switch target.kind { case "json": path := processNegativeIndex(data, target.key) @@ -1545,7 +1542,7 @@ func readSyncTargetValue(data []byte, context map[string]interface{}, target syn } } -func writeSyncTargetValue(data []byte, context map[string]interface{}, target syncTarget, value interface{}) ([]byte, error) { +func writeSyncTargetValue(data []byte, context map[string]any, target syncTarget, value any) ([]byte, error) { switch target.kind { case "json": path := processNegativeIndex(data, target.key) @@ -1564,7 +1561,7 @@ func writeSyncTargetValue(data []byte, context map[string]interface{}, target sy } } -func syncFieldsBetweenTargets(data []byte, context map[string]interface{}, fromSpec string, toSpec string) ([]byte, error) { +func syncFieldsBetweenTargets(data []byte, context map[string]any, fromSpec string, toSpec string) ([]byte, error) { fromTarget, err := parseSyncTarget(fromSpec) if err != nil { return nil, err @@ -1593,21 +1590,21 @@ func syncFieldsBetweenTargets(data []byte, context map[string]interface{}, fromS return data, nil } -func ensureMapKeyInContext(context map[string]interface{}, key string) map[string]interface{} { +func ensureMapKeyInContext(context map[string]any, key string) map[string]any { if context == nil { - return map[string]interface{}{} + return map[string]any{} } if existing, ok := context[key]; ok { - if mapVal, ok := existing.(map[string]interface{}); ok { + if mapVal, ok := existing.(map[string]any); ok { return mapVal } } - result := make(map[string]interface{}) + result := make(map[string]any) context[key] = result return result } -func getHeaderValueFromContext(context map[string]interface{}, headerName string) (string, bool) { +func getHeaderValueFromContext(context map[string]any, headerName string) (string, bool) { headerName = normalizeHeaderContextKey(headerName) if headerName == "" { return "", false @@ -1630,9 +1627,9 @@ func normalizeHeaderContextKey(key string) string { return strings.TrimSpace(strings.ToLower(key)) } -func buildRequestHeadersContext(headers map[string]string) map[string]interface{} { +func buildRequestHeadersContext(headers map[string]string) map[string]any { if len(headers) == 0 { - return map[string]interface{}{} + return map[string]any{} } entries := lo.Entries(headers) normalizedEntries := lo.FilterMap(entries, func(item lo.Entry[string, string], _ int) (lo.Entry[string, string], bool) { @@ -1643,12 +1640,12 @@ func buildRequestHeadersContext(headers map[string]string) map[string]interface{ } return lo.Entry[string, string]{Key: normalized, Value: value}, true }) - return lo.SliceToMap(normalizedEntries, func(item lo.Entry[string, string]) (string, interface{}) { + return lo.SliceToMap(normalizedEntries, func(item lo.Entry[string, string]) (string, any) { return item.Key, item.Value }) } -func syncRuntimeHeaderOverrideFromContext(info *RelayInfo, context map[string]interface{}) { +func syncRuntimeHeaderOverrideFromContext(info *RelayInfo, context map[string]any) { if info == nil || context == nil { return } @@ -1656,7 +1653,7 @@ func syncRuntimeHeaderOverrideFromContext(info *RelayInfo, context map[string]in if !exists { return } - rawMap, ok := raw.(map[string]interface{}) + rawMap, ok := raw.(map[string]any) if !ok { return } @@ -1701,7 +1698,7 @@ func resolveOperationPaths(data []byte, path string) ([]string, error) { } func expandWildcardPaths(data []byte, path string) ([]string, error) { - var root interface{} + var root any if err := common.Unmarshal(data, &root); err != nil { return nil, err } @@ -1711,7 +1708,7 @@ func expandWildcardPaths(data []byte, path string) ([]string, error) { return lo.Uniq(paths), nil } -func collectWildcardPaths(node interface{}, segments []string, prefix []string) []string { +func collectWildcardPaths(node any, segments []string, prefix []string) []string { if len(segments) == 0 { return []string{strings.Join(prefix, ".")} } @@ -1724,13 +1721,13 @@ func collectWildcardPaths(node interface{}, segments []string, prefix []string) if segment == "*" { switch typed := node.(type) { - case map[string]interface{}: + case map[string]any: keys := lo.Keys(typed) sort.Strings(keys) return lo.FlatMap(keys, func(key string, _ int) []string { return collectWildcardPaths(typed[key], segments[1:], append(prefix, key)) }) - case []interface{}: + case []any: return lo.FlatMap(lo.Range(len(typed)), func(index int, _ int) []string { return collectWildcardPaths(typed[index], segments[1:], append(prefix, strconv.Itoa(index))) }) @@ -1740,7 +1737,7 @@ func collectWildcardPaths(node interface{}, segments []string, prefix []string) } switch typed := node.(type) { - case map[string]interface{}: + case map[string]any: if isLast { return []string{strings.Join(append(prefix, segment), ".")} } @@ -1749,7 +1746,7 @@ func collectWildcardPaths(node interface{}, segments []string, prefix []string) return nil } return collectWildcardPaths(next, segments[1:], append(prefix, segment)) - case []interface{}: + case []any: index, err := strconv.Atoi(segment) if err != nil || index < 0 || index >= len(typed) { return nil @@ -1770,7 +1767,7 @@ func deleteValue(data []byte, path string) ([]byte, error) { return sjson.DeleteBytes(data, path) } -func modifyValue(data []byte, path string, value interface{}, keepOrigin, isPrepend bool) ([]byte, error) { +func modifyValue(data []byte, path string, value any, keepOrigin, isPrepend bool) ([]byte, error) { current := gjson.GetBytes(data, path) switch { case current.IsArray(): @@ -1783,12 +1780,12 @@ func modifyValue(data []byte, path string, value interface{}, keepOrigin, isPrep return data, fmt.Errorf("operation not supported for type: %v", current.Type) } -func modifyArray(data []byte, path string, value interface{}, isPrepend bool) ([]byte, error) { +func modifyArray(data []byte, path string, value any, isPrepend bool) ([]byte, error) { current := gjson.GetBytes(data, path) - var newArray []interface{} + var newArray []any // 添加新值 addValue := func() { - if arr, ok := value.([]interface{}); ok { + if arr, ok := value.([]any); ok { newArray = append(newArray, arr...) } else { newArray = append(newArray, value) @@ -1811,7 +1808,7 @@ func modifyArray(data []byte, path string, value interface{}, isPrepend bool) ([ return sjson.SetBytes(data, path, newArray) } -func modifyString(data []byte, path string, value interface{}, isPrepend bool) ([]byte, error) { +func modifyString(data []byte, path string, value any, isPrepend bool) ([]byte, error) { current := gjson.GetBytes(data, path) valueStr := fmt.Sprintf("%v", value) var newStr string @@ -1823,7 +1820,7 @@ func modifyString(data []byte, path string, value interface{}, isPrepend bool) ( return sjson.SetBytes(data, path, newStr) } -func trimStringValue(data []byte, path string, value interface{}, isPrefix bool) ([]byte, error) { +func trimStringValue(data []byte, path string, value any, isPrefix bool) ([]byte, error) { current := gjson.GetBytes(data, path) if current.Type != gjson.String { return data, fmt.Errorf("operation not supported for type: %v", current.Type) @@ -1843,7 +1840,7 @@ func trimStringValue(data []byte, path string, value interface{}, isPrefix bool) return sjson.SetBytes(data, path, newStr) } -func ensureStringAffix(data []byte, path string, value interface{}, isPrefix bool) ([]byte, error) { +func ensureStringAffix(data []byte, path string, value any, isPrefix bool) ([]byte, error) { current := gjson.GetBytes(data, path) if current.Type != gjson.String { return data, fmt.Errorf("operation not supported for type: %v", current.Type) @@ -1911,14 +1908,14 @@ type pruneObjectsOptions struct { recursive bool } -func pruneObjects(data []byte, path, contextJSON string, value interface{}) ([]byte, error) { +func pruneObjects(data []byte, path, contextJSON string, value any) ([]byte, error) { options, err := parsePruneObjectsOptions(value) if err != nil { return nil, err } if path == "" { - var root interface{} + var root any if err := common.Unmarshal(data, &root); err != nil { return nil, err } @@ -1934,7 +1931,7 @@ func pruneObjects(data []byte, path, contextJSON string, value interface{}) ([]b return data, nil } - var targetNode interface{} + var targetNode any if target.Type == gjson.JSON { if err := common.UnmarshalJsonStr(target.Raw, &targetNode); err != nil { return nil, err @@ -1954,7 +1951,7 @@ func pruneObjects(data []byte, path, contextJSON string, value interface{}) ([]b return sjson.SetRawBytes(data, path, cleanedBytes) } -func parsePruneObjectsOptions(value interface{}) (pruneObjectsOptions, error) { +func parsePruneObjectsOptions(value any) (pruneObjectsOptions, error) { opts := pruneObjectsOptions{ logic: "AND", recursive: true, @@ -1975,7 +1972,7 @@ func parsePruneObjectsOptions(value interface{}) (pruneObjectsOptions, error) { Value: v, }, } - case map[string]interface{}: + case map[string]any: if logic, ok := raw["logic"].(string); ok && strings.TrimSpace(logic) != "" { opts.logic = logic } @@ -1992,7 +1989,7 @@ func parsePruneObjectsOptions(value interface{}) (pruneObjectsOptions, error) { } if whereRaw, exists := raw["where"]; exists { - whereMap, ok := whereRaw.(map[string]interface{}) + whereMap, ok := whereRaw.(map[string]any) if !ok { return opts, fmt.Errorf("prune_objects where must be object") } @@ -2026,11 +2023,11 @@ func parsePruneObjectsOptions(value interface{}) (pruneObjectsOptions, error) { return opts, nil } -func parseConditionOperations(raw interface{}) ([]ConditionOperation, error) { +func parseConditionOperations(raw any) ([]ConditionOperation, error) { switch typed := raw.(type) { - case map[string]interface{}: + case map[string]any: entries := lo.Entries(typed) - conditions := lo.FilterMap(entries, func(item lo.Entry[string, interface{}], _ int) (ConditionOperation, bool) { + conditions := lo.FilterMap(entries, func(item lo.Entry[string, any], _ int) (ConditionOperation, bool) { path := strings.TrimSpace(item.Key) if path == "" { return ConditionOperation{}, false @@ -2045,11 +2042,11 @@ func parseConditionOperations(raw interface{}) ([]ConditionOperation, error) { return nil, fmt.Errorf("conditions object must contain at least one key") } return conditions, nil - case []interface{}: + case []any: items := typed result := make([]ConditionOperation, 0, len(items)) for _, item := range items { - itemMap, ok := item.(map[string]interface{}) + itemMap, ok := item.(map[string]any) if !ok { return nil, fmt.Errorf("condition must be object") } @@ -2079,10 +2076,10 @@ func parseConditionOperations(raw interface{}) ([]ConditionOperation, error) { } } -func pruneObjectsNode(node interface{}, options pruneObjectsOptions, contextJSON string, isRoot bool) (interface{}, bool, error) { +func pruneObjectsNode(node any, options pruneObjectsOptions, contextJSON string, isRoot bool) (any, bool, error) { switch value := node.(type) { - case []interface{}: - result := make([]interface{}, 0, len(value)) + case []any: + result := make([]any, 0, len(value)) for _, item := range value { next, drop, err := pruneObjectsNode(item, options, contextJSON, false) if err != nil { @@ -2094,7 +2091,7 @@ func pruneObjectsNode(node interface{}, options pruneObjectsOptions, contextJSON result = append(result, next) } return result, false, nil - case map[string]interface{}: + case map[string]any: shouldDrop, err := shouldPruneObject(value, options, contextJSON) if err != nil { return nil, false, err @@ -2122,7 +2119,7 @@ func pruneObjectsNode(node interface{}, options pruneObjectsOptions, contextJSON } } -func shouldPruneObject(node map[string]interface{}, options pruneObjectsOptions, contextJSON string) (bool, error) { +func shouldPruneObject(node map[string]any, options pruneObjectsOptions, contextJSON string) (bool, error) { nodeBytes, err := common.Marshal(node) if err != nil { return false, err @@ -2130,9 +2127,9 @@ func shouldPruneObject(node map[string]interface{}, options pruneObjectsOptions, return checkConditions(nodeBytes, contextJSON, options.conditions, options.logic) } -func mergeObjects(data []byte, path string, value interface{}, keepOrigin bool) ([]byte, error) { +func mergeObjects(data []byte, path string, value any, keepOrigin bool) ([]byte, error) { current := gjson.GetBytes(data, path) - var currentMap, newMap map[string]interface{} + var currentMap, newMap map[string]any // 解析当前值(current.Raw 是 data 的子串,避免再分配一份) if err := common.UnmarshalJsonStr(current.Raw, ¤tMap); err != nil { @@ -2140,7 +2137,7 @@ func mergeObjects(data []byte, path string, value interface{}, keepOrigin bool) } // 解析新值 switch v := value.(type) { - case map[string]interface{}: + case map[string]any: newMap = v default: jsonBytes, _ := common.Marshal(v) @@ -2149,10 +2146,8 @@ func mergeObjects(data []byte, path string, value interface{}, keepOrigin bool) } } // 合并 - result := make(map[string]interface{}) - for k, v := range currentMap { - result[k] = v - } + result := make(map[string]any) + maps.Copy(result, currentMap) for k, v := range newMap { if !keepOrigin || result[k] == nil { result[k] = v @@ -2171,12 +2166,12 @@ func mergeObjects(data []byte, path string, value interface{}, keepOrigin bool) // - using_group:当前实际使用的分组,自动跨分组重试时可能变化。 // - request_path:请求路径 // - is_channel_test:是否为渠道测试请求(同 is_test)。 -func BuildParamOverrideContext(info *RelayInfo) map[string]interface{} { +func BuildParamOverrideContext(info *RelayInfo) map[string]any { if info == nil { return nil } - ctx := make(map[string]interface{}) + ctx := make(map[string]any) ctx["user_id"] = info.UserId ctx["user_group"] = info.UserGroup ctx["token_group"] = info.TokenGroup @@ -2206,7 +2201,7 @@ func BuildParamOverrideContext(info *RelayInfo) map[string]interface{} { ctx["retry_index"] = info.RetryIndex ctx["is_retry"] = info.RetryIndex > 0 - ctx["retry"] = map[string]interface{}{ + ctx["retry"] = map[string]any{ "index": info.RetryIndex, "is_retry": info.RetryIndex > 0, } @@ -2214,7 +2209,7 @@ func BuildParamOverrideContext(info *RelayInfo) map[string]interface{} { if info.LastError != nil { code := string(info.LastError.GetErrorCode()) errorType := string(info.LastError.GetErrorType()) - lastError := map[string]interface{}{ + lastError := map[string]any{ "status_code": info.LastError.StatusCode, "message": info.LastError.Error(), "code": code, diff --git a/relay/common/override_test.go b/relay/common/override_test.go index 19af348df9..4d958b2ec4 100644 --- a/relay/common/override_test.go +++ b/relay/common/override_test.go @@ -20,9 +20,9 @@ func TestApplyParamOverrideTrimPrefix(t *testing.T) { // trim_prefix example: // {"operations":[{"path":"model","mode":"trim_prefix","value":"openai/"}]} input := []byte(`{"model":"openai/gpt-4","temperature":0.7}`) - override := map[string]interface{}{ - "operations": []interface{}{ - map[string]interface{}{ + override := map[string]any{ + "operations": []any{ + map[string]any{ "path": "model", "mode": "trim_prefix", "value": "openai/", @@ -41,9 +41,9 @@ func TestApplyParamOverrideTrimSuffix(t *testing.T) { // trim_suffix example: // {"operations":[{"path":"model","mode":"trim_suffix","value":"-latest"}]} input := []byte(`{"model":"gpt-4-latest","temperature":0.7}`) - override := map[string]interface{}{ - "operations": []interface{}{ - map[string]interface{}{ + override := map[string]any{ + "operations": []any{ + map[string]any{ "path": "model", "mode": "trim_suffix", "value": "-latest", @@ -62,9 +62,9 @@ func TestApplyParamOverrideTrimNoop(t *testing.T) { // trim_prefix no-op example: // {"operations":[{"path":"model","mode":"trim_prefix","value":"openai/"}]} input := []byte(`{"model":"gpt-4","temperature":0.7}`) - override := map[string]interface{}{ - "operations": []interface{}{ - map[string]interface{}{ + override := map[string]any{ + "operations": []any{ + map[string]any{ "path": "model", "mode": "trim_prefix", "value": "openai/", @@ -81,11 +81,11 @@ func TestApplyParamOverrideTrimNoop(t *testing.T) { func TestApplyParamOverrideMixedLegacyAndOperations(t *testing.T) { input := []byte(`{"model":"openai/gpt-4","temperature":0.7}`) - override := map[string]interface{}{ + override := map[string]any{ "temperature": 0.2, "top_p": 0.95, - "operations": []interface{}{ - map[string]interface{}{ + "operations": []any{ + map[string]any{ "path": "model", "mode": "trim_prefix", "value": "openai/", @@ -102,11 +102,11 @@ func TestApplyParamOverrideMixedLegacyAndOperations(t *testing.T) { func TestApplyParamOverrideMixedLegacyAndOperationsConflictPrefersOperations(t *testing.T) { input := []byte(`{"model":"openai/gpt-4","temperature":0.7}`) - override := map[string]interface{}{ + override := map[string]any{ "model": "legacy-model", "temperature": 0.2, - "operations": []interface{}{ - map[string]interface{}{ + "operations": []any{ + map[string]any{ "path": "model", "mode": "set", "value": "op-model", @@ -125,9 +125,9 @@ func TestApplyParamOverrideTrimRequiresValue(t *testing.T) { // trim_prefix requires value example: // {"operations":[{"path":"model","mode":"trim_prefix"}]} input := []byte(`{"model":"gpt-4"}`) - override := map[string]interface{}{ - "operations": []interface{}{ - map[string]interface{}{ + override := map[string]any{ + "operations": []any{ + map[string]any{ "path": "model", "mode": "trim_prefix", }, @@ -144,9 +144,9 @@ func TestApplyParamOverrideReplace(t *testing.T) { // replace example: // {"operations":[{"path":"model","mode":"replace","from":"openai/","to":""}]} input := []byte(`{"model":"openai/gpt-4o-mini","temperature":0.7}`) - override := map[string]interface{}{ - "operations": []interface{}{ - map[string]interface{}{ + override := map[string]any{ + "operations": []any{ + map[string]any{ "path": "model", "mode": "replace", "from": "openai/", @@ -166,9 +166,9 @@ func TestApplyParamOverrideRegexReplace(t *testing.T) { // regex_replace example: // {"operations":[{"path":"model","mode":"regex_replace","from":"^gpt-","to":"openai/gpt-"}]} input := []byte(`{"model":"gpt-4o-mini","temperature":0.7}`) - override := map[string]interface{}{ - "operations": []interface{}{ - map[string]interface{}{ + override := map[string]any{ + "operations": []any{ + map[string]any{ "path": "model", "mode": "regex_replace", "from": "^gpt-", @@ -188,9 +188,9 @@ func TestApplyParamOverrideReplaceRequiresFrom(t *testing.T) { // replace requires from example: // {"operations":[{"path":"model","mode":"replace"}]} input := []byte(`{"model":"gpt-4"}`) - override := map[string]interface{}{ - "operations": []interface{}{ - map[string]interface{}{ + override := map[string]any{ + "operations": []any{ + map[string]any{ "path": "model", "mode": "replace", }, @@ -207,9 +207,9 @@ func TestApplyParamOverrideRegexReplaceRequiresPattern(t *testing.T) { // regex_replace requires from(pattern) example: // {"operations":[{"path":"model","mode":"regex_replace"}]} input := []byte(`{"model":"gpt-4"}`) - override := map[string]interface{}{ - "operations": []interface{}{ - map[string]interface{}{ + override := map[string]any{ + "operations": []any{ + map[string]any{ "path": "model", "mode": "regex_replace", }, @@ -224,9 +224,9 @@ func TestApplyParamOverrideRegexReplaceRequiresPattern(t *testing.T) { func TestApplyParamOverrideDelete(t *testing.T) { input := []byte(`{"model":"gpt-4","temperature":0.7}`) - override := map[string]interface{}{ - "operations": []interface{}{ - map[string]interface{}{ + override := map[string]any{ + "operations": []any{ + map[string]any{ "path": "temperature", "mode": "delete", }, @@ -238,7 +238,7 @@ func TestApplyParamOverrideDelete(t *testing.T) { t.Fatalf("ApplyParamOverride returned error: %v", err) } - var got map[string]interface{} + var got map[string]any if err := json.Unmarshal(out, &got); err != nil { t.Fatalf("failed to unmarshal output JSON: %v", err) } @@ -249,9 +249,9 @@ func TestApplyParamOverrideDelete(t *testing.T) { func TestApplyParamOverrideDeleteWildcardPath(t *testing.T) { input := []byte(`{"tools":[{"type":"bash","custom":{"input_examples":["a"],"other":1}},{"type":"code","custom":{"input_examples":["b"]}},{"type":"noop","custom":{"other":2}}]}`) - override := map[string]interface{}{ - "operations": []interface{}{ - map[string]interface{}{ + override := map[string]any{ + "operations": []any{ + map[string]any{ "path": "tools.*.custom.input_examples", "mode": "delete", }, @@ -267,9 +267,9 @@ func TestApplyParamOverrideDeleteWildcardPath(t *testing.T) { func TestApplyParamOverrideSetWildcardPath(t *testing.T) { input := []byte(`{"tools":[{"custom":{"tag":"A"}},{"custom":{"tag":"B"}},{"custom":{"tag":"C"}}]}`) - override := map[string]interface{}{ - "operations": []interface{}{ - map[string]interface{}{ + override := map[string]any{ + "operations": []any{ + map[string]any{ "path": "tools.*.custom.enabled", "mode": "set", "value": true, @@ -306,9 +306,9 @@ func TestApplyParamOverrideSetWildcardPath(t *testing.T) { func TestApplyParamOverrideTrimSpaceWildcardPath(t *testing.T) { input := []byte(`{"tools":[{"custom":{"name":" alpha "}},{"custom":{"name":" beta"}},{"custom":{"name":"gamma "}}]}`) - override := map[string]interface{}{ - "operations": []interface{}{ - map[string]interface{}{ + override := map[string]any{ + "operations": []any{ + map[string]any{ "path": "tools.*.custom.name", "mode": "trim_space", }, @@ -346,18 +346,18 @@ func TestApplyParamOverrideTrimSpaceWildcardPath(t *testing.T) { func TestApplyParamOverrideDeleteWildcardEqualsIndexedPaths(t *testing.T) { input := []byte(`{"tools":[{"custom":{"input_examples":["a"],"other":1}},{"custom":{"input_examples":["b"],"other":2}},{"custom":{"input_examples":["c"],"other":3}}]}`) - wildcardOverride := map[string]interface{}{ - "operations": []interface{}{ - map[string]interface{}{ + wildcardOverride := map[string]any{ + "operations": []any{ + map[string]any{ "path": "tools.*.custom.input_examples", "mode": "delete", }, }, } - indexedOverride := map[string]interface{}{ - "operations": lo.Map(lo.Range(3), func(index int, _ int) interface{} { - return map[string]interface{}{ + indexedOverride := map[string]any{ + "operations": lo.Map(lo.Range(3), func(index int, _ int) any { + return map[string]any{ "path": fmt.Sprintf("tools.%d.custom.input_examples", index), "mode": "delete", } @@ -379,9 +379,9 @@ func TestApplyParamOverrideDeleteWildcardEqualsIndexedPaths(t *testing.T) { func TestApplyParamOverrideSetWildcardKeepOrigin(t *testing.T) { input := []byte(`{"tools":[{"custom":{"tag":"A"}},{"custom":{"tag":"B","enabled":false}},{"custom":{"tag":"C"}}]}`) - override := map[string]interface{}{ - "operations": []interface{}{ - map[string]interface{}{ + override := map[string]any{ + "operations": []any{ + map[string]any{ "path": "tools.*.custom.enabled", "mode": "set", "value": true, @@ -420,9 +420,9 @@ func TestApplyParamOverrideSetWildcardKeepOrigin(t *testing.T) { func TestApplyParamOverrideTrimSpaceMultiWildcardPath(t *testing.T) { input := []byte(`{"tools":[{"custom":{"items":[{"name":" alpha "},{"name":" beta "}]}},{"custom":{"items":[{"name":" gamma"}]}}]}`) - override := map[string]interface{}{ - "operations": []interface{}{ - map[string]interface{}{ + override := map[string]any{ + "operations": []any{ + map[string]any{ "path": "tools.*.custom.items.*.name", "mode": "trim_space", }, @@ -467,9 +467,9 @@ func TestApplyParamOverrideTrimSpaceMultiWildcardPath(t *testing.T) { func TestApplyParamOverrideSet(t *testing.T) { input := []byte(`{"model":"gpt-4","temperature":0.7}`) - override := map[string]interface{}{ - "operations": []interface{}{ - map[string]interface{}{ + override := map[string]any{ + "operations": []any{ + map[string]any{ "path": "temperature", "mode": "set", "value": 0.1, @@ -486,18 +486,18 @@ func TestApplyParamOverrideSet(t *testing.T) { func TestApplyParamOverrideSetWithDescriptionKeepsCompatibility(t *testing.T) { input := []byte(`{"model":"gpt-4","temperature":0.7}`) - overrideWithoutDesc := map[string]interface{}{ - "operations": []interface{}{ - map[string]interface{}{ + overrideWithoutDesc := map[string]any{ + "operations": []any{ + map[string]any{ "path": "temperature", "mode": "set", "value": 0.1, }, }, } - overrideWithDesc := map[string]interface{}{ - "operations": []interface{}{ - map[string]interface{}{ + overrideWithDesc := map[string]any{ + "operations": []any{ + map[string]any{ "description": "set temperature for deterministic output", "path": "temperature", "mode": "set", @@ -522,9 +522,9 @@ func TestApplyParamOverrideSetWithDescriptionKeepsCompatibility(t *testing.T) { func TestApplyParamOverrideSetKeepOrigin(t *testing.T) { input := []byte(`{"model":"gpt-4","temperature":0.7}`) - override := map[string]interface{}{ - "operations": []interface{}{ - map[string]interface{}{ + override := map[string]any{ + "operations": []any{ + map[string]any{ "path": "temperature", "mode": "set", "value": 0.1, @@ -542,9 +542,9 @@ func TestApplyParamOverrideSetKeepOrigin(t *testing.T) { func TestApplyParamOverrideMove(t *testing.T) { input := []byte(`{"model":"gpt-4","meta":{"x":1}}`) - override := map[string]interface{}{ - "operations": []interface{}{ - map[string]interface{}{ + override := map[string]any{ + "operations": []any{ + map[string]any{ "mode": "move", "from": "model", "to": "meta.model", @@ -561,9 +561,9 @@ func TestApplyParamOverrideMove(t *testing.T) { func TestApplyParamOverrideMoveMissingSource(t *testing.T) { input := []byte(`{"meta":{"x":1}}`) - override := map[string]interface{}{ - "operations": []interface{}{ - map[string]interface{}{ + override := map[string]any{ + "operations": []any{ + map[string]any{ "mode": "move", "from": "model", "to": "meta.model", @@ -579,14 +579,14 @@ func TestApplyParamOverrideMoveMissingSource(t *testing.T) { func TestApplyParamOverridePrependAppendString(t *testing.T) { input := []byte(`{"model":"gpt-4"}`) - override := map[string]interface{}{ - "operations": []interface{}{ - map[string]interface{}{ + override := map[string]any{ + "operations": []any{ + map[string]any{ "path": "model", "mode": "prepend", "value": "openai/", }, - map[string]interface{}{ + map[string]any{ "path": "model", "mode": "append", "value": "-latest", @@ -603,17 +603,17 @@ func TestApplyParamOverridePrependAppendString(t *testing.T) { func TestApplyParamOverridePrependAppendArray(t *testing.T) { input := []byte(`{"arr":[1,2]}`) - override := map[string]interface{}{ - "operations": []interface{}{ - map[string]interface{}{ + override := map[string]any{ + "operations": []any{ + map[string]any{ "path": "arr", "mode": "prepend", "value": 0, }, - map[string]interface{}{ + map[string]any{ "path": "arr", "mode": "append", - "value": []interface{}{3, 4}, + "value": []any{3, 4}, }, }, } @@ -627,13 +627,13 @@ func TestApplyParamOverridePrependAppendArray(t *testing.T) { func TestApplyParamOverrideAppendObjectMergeKeepOrigin(t *testing.T) { input := []byte(`{"obj":{"a":1}}`) - override := map[string]interface{}{ - "operations": []interface{}{ - map[string]interface{}{ + override := map[string]any{ + "operations": []any{ + map[string]any{ "path": "obj", "mode": "append", "keep_origin": true, - "value": map[string]interface{}{ + "value": map[string]any{ "a": 2, "b": 3, }, @@ -650,12 +650,12 @@ func TestApplyParamOverrideAppendObjectMergeKeepOrigin(t *testing.T) { func TestApplyParamOverrideAppendObjectMergeOverride(t *testing.T) { input := []byte(`{"obj":{"a":1}}`) - override := map[string]interface{}{ - "operations": []interface{}{ - map[string]interface{}{ + override := map[string]any{ + "operations": []any{ + map[string]any{ "path": "obj", "mode": "append", - "value": map[string]interface{}{ + "value": map[string]any{ "a": 2, "b": 3, }, @@ -672,19 +672,19 @@ func TestApplyParamOverrideAppendObjectMergeOverride(t *testing.T) { func TestApplyParamOverrideConditionORDefault(t *testing.T) { input := []byte(`{"model":"gpt-4","temperature":0.7}`) - override := map[string]interface{}{ - "operations": []interface{}{ - map[string]interface{}{ + override := map[string]any{ + "operations": []any{ + map[string]any{ "path": "temperature", "mode": "set", "value": 0.1, - "conditions": []interface{}{ - map[string]interface{}{ + "conditions": []any{ + map[string]any{ "path": "model", "mode": "prefix", "value": "gpt", }, - map[string]interface{}{ + map[string]any{ "path": "model", "mode": "prefix", "value": "claude", @@ -703,20 +703,20 @@ func TestApplyParamOverrideConditionORDefault(t *testing.T) { func TestApplyParamOverrideConditionAND(t *testing.T) { input := []byte(`{"model":"gpt-4","temperature":0.7}`) - override := map[string]interface{}{ - "operations": []interface{}{ - map[string]interface{}{ + override := map[string]any{ + "operations": []any{ + map[string]any{ "path": "temperature", "mode": "set", "value": 0.1, "logic": "AND", - "conditions": []interface{}{ - map[string]interface{}{ + "conditions": []any{ + map[string]any{ "path": "model", "mode": "prefix", "value": "gpt", }, - map[string]interface{}{ + map[string]any{ "path": "temperature", "mode": "gt", "value": 0.5, @@ -735,14 +735,14 @@ func TestApplyParamOverrideConditionAND(t *testing.T) { func TestApplyParamOverrideConditionInvert(t *testing.T) { input := []byte(`{"model":"gpt-4","temperature":0.7}`) - override := map[string]interface{}{ - "operations": []interface{}{ - map[string]interface{}{ + override := map[string]any{ + "operations": []any{ + map[string]any{ "path": "temperature", "mode": "set", "value": 0.1, - "conditions": []interface{}{ - map[string]interface{}{ + "conditions": []any{ + map[string]any{ "path": "model", "mode": "prefix", "value": "gpt", @@ -762,14 +762,14 @@ func TestApplyParamOverrideConditionInvert(t *testing.T) { func TestApplyParamOverrideConditionPassMissingKey(t *testing.T) { input := []byte(`{"temperature":0.7}`) - override := map[string]interface{}{ - "operations": []interface{}{ - map[string]interface{}{ + override := map[string]any{ + "operations": []any{ + map[string]any{ "path": "temperature", "mode": "set", "value": 0.1, - "conditions": []interface{}{ - map[string]interface{}{ + "conditions": []any{ + map[string]any{ "path": "model", "mode": "prefix", "value": "gpt", @@ -789,14 +789,14 @@ func TestApplyParamOverrideConditionPassMissingKey(t *testing.T) { func TestApplyParamOverrideConditionFromContext(t *testing.T) { input := []byte(`{"temperature":0.7}`) - override := map[string]interface{}{ - "operations": []interface{}{ - map[string]interface{}{ + override := map[string]any{ + "operations": []any{ + map[string]any{ "path": "temperature", "mode": "set", "value": 0.1, - "conditions": []interface{}{ - map[string]interface{}{ + "conditions": []any{ + map[string]any{ "path": "model", "mode": "prefix", "value": "gpt", @@ -805,7 +805,7 @@ func TestApplyParamOverrideConditionFromContext(t *testing.T) { }, }, } - ctx := map[string]interface{}{ + ctx := map[string]any{ "model": "gpt-4", } @@ -818,9 +818,9 @@ func TestApplyParamOverrideConditionFromContext(t *testing.T) { func TestApplyParamOverrideNegativeIndexPath(t *testing.T) { input := []byte(`{"arr":[{"model":"a"},{"model":"b"}]}`) - override := map[string]interface{}{ - "operations": []interface{}{ - map[string]interface{}{ + override := map[string]any{ + "operations": []any{ + map[string]any{ "path": "arr.-1.model", "mode": "set", "value": "c", @@ -839,9 +839,9 @@ func TestApplyParamOverrideRegexReplaceInvalidPattern(t *testing.T) { // regex_replace invalid pattern example: // {"operations":[{"path":"model","mode":"regex_replace","from":"(","to":"x"}]} input := []byte(`{"model":"gpt-4"}`) - override := map[string]interface{}{ - "operations": []interface{}{ - map[string]interface{}{ + override := map[string]any{ + "operations": []any{ + map[string]any{ "path": "model", "mode": "regex_replace", "from": "(", @@ -860,9 +860,9 @@ func TestApplyParamOverrideCopy(t *testing.T) { // copy example: // {"operations":[{"mode":"copy","from":"model","to":"original_model"}]} input := []byte(`{"model":"gpt-4","temperature":0.7}`) - override := map[string]interface{}{ - "operations": []interface{}{ - map[string]interface{}{ + override := map[string]any{ + "operations": []any{ + map[string]any{ "mode": "copy", "from": "model", "to": "original_model", @@ -881,9 +881,9 @@ func TestApplyParamOverrideCopyMissingSource(t *testing.T) { // copy missing source example: // {"operations":[{"mode":"copy","from":"model","to":"original_model"}]} input := []byte(`{"temperature":0.7}`) - override := map[string]interface{}{ - "operations": []interface{}{ - map[string]interface{}{ + override := map[string]any{ + "operations": []any{ + map[string]any{ "mode": "copy", "from": "model", "to": "original_model", @@ -901,9 +901,9 @@ func TestApplyParamOverrideCopyRequiresFromTo(t *testing.T) { // copy requires from/to example: // {"operations":[{"mode":"copy"}]} input := []byte(`{"model":"gpt-4"}`) - override := map[string]interface{}{ - "operations": []interface{}{ - map[string]interface{}{ + override := map[string]any{ + "operations": []any{ + map[string]any{ "mode": "copy", }, }, @@ -919,9 +919,9 @@ func TestApplyParamOverrideEnsurePrefix(t *testing.T) { // ensure_prefix example: // {"operations":[{"path":"model","mode":"ensure_prefix","value":"openai/"}]} input := []byte(`{"model":"gpt-4"}`) - override := map[string]interface{}{ - "operations": []interface{}{ - map[string]interface{}{ + override := map[string]any{ + "operations": []any{ + map[string]any{ "path": "model", "mode": "ensure_prefix", "value": "openai/", @@ -940,9 +940,9 @@ func TestApplyParamOverrideEnsurePrefixNoop(t *testing.T) { // ensure_prefix no-op example: // {"operations":[{"path":"model","mode":"ensure_prefix","value":"openai/"}]} input := []byte(`{"model":"openai/gpt-4"}`) - override := map[string]interface{}{ - "operations": []interface{}{ - map[string]interface{}{ + override := map[string]any{ + "operations": []any{ + map[string]any{ "path": "model", "mode": "ensure_prefix", "value": "openai/", @@ -961,9 +961,9 @@ func TestApplyParamOverrideEnsureSuffix(t *testing.T) { // ensure_suffix example: // {"operations":[{"path":"model","mode":"ensure_suffix","value":"-latest"}]} input := []byte(`{"model":"gpt-4"}`) - override := map[string]interface{}{ - "operations": []interface{}{ - map[string]interface{}{ + override := map[string]any{ + "operations": []any{ + map[string]any{ "path": "model", "mode": "ensure_suffix", "value": "-latest", @@ -982,9 +982,9 @@ func TestApplyParamOverrideEnsureSuffixNoop(t *testing.T) { // ensure_suffix no-op example: // {"operations":[{"path":"model","mode":"ensure_suffix","value":"-latest"}]} input := []byte(`{"model":"gpt-4-latest"}`) - override := map[string]interface{}{ - "operations": []interface{}{ - map[string]interface{}{ + override := map[string]any{ + "operations": []any{ + map[string]any{ "path": "model", "mode": "ensure_suffix", "value": "-latest", @@ -1003,9 +1003,9 @@ func TestApplyParamOverrideEnsureRequiresValue(t *testing.T) { // ensure_prefix requires value example: // {"operations":[{"path":"model","mode":"ensure_prefix"}]} input := []byte(`{"model":"gpt-4"}`) - override := map[string]interface{}{ - "operations": []interface{}{ - map[string]interface{}{ + override := map[string]any{ + "operations": []any{ + map[string]any{ "path": "model", "mode": "ensure_prefix", }, @@ -1022,9 +1022,9 @@ func TestApplyParamOverrideTrimSpace(t *testing.T) { // trim_space example: // {"operations":[{"path":"model","mode":"trim_space"}]} input := []byte("{\"model\":\" gpt-4 \\n\"}") - override := map[string]interface{}{ - "operations": []interface{}{ - map[string]interface{}{ + override := map[string]any{ + "operations": []any{ + map[string]any{ "path": "model", "mode": "trim_space", }, @@ -1042,9 +1042,9 @@ func TestApplyParamOverrideToLower(t *testing.T) { // to_lower example: // {"operations":[{"path":"model","mode":"to_lower"}]} input := []byte(`{"model":"GPT-4"}`) - override := map[string]interface{}{ - "operations": []interface{}{ - map[string]interface{}{ + override := map[string]any{ + "operations": []any{ + map[string]any{ "path": "model", "mode": "to_lower", }, @@ -1062,9 +1062,9 @@ func TestApplyParamOverrideToUpper(t *testing.T) { // to_upper example: // {"operations":[{"path":"model","mode":"to_upper"}]} input := []byte(`{"model":"gpt-4"}`) - override := map[string]interface{}{ - "operations": []interface{}{ - map[string]interface{}{ + override := map[string]any{ + "operations": []any{ + map[string]any{ "path": "model", "mode": "to_upper", }, @@ -1080,19 +1080,19 @@ func TestApplyParamOverrideToUpper(t *testing.T) { func TestApplyParamOverrideReturnError(t *testing.T) { input := []byte(`{"model":"gemini-2.5-pro"}`) - override := map[string]interface{}{ - "operations": []interface{}{ - map[string]interface{}{ + override := map[string]any{ + "operations": []any{ + map[string]any{ "mode": "return_error", - "value": map[string]interface{}{ + "value": map[string]any{ "message": "forced bad request by param override", "status_code": 422, "code": "forced_bad_request", "type": "invalid_request_error", "skip_retry": true, }, - "conditions": []interface{}{ - map[string]interface{}{ + "conditions": []any{ + map[string]any{ "path": "retry.is_retry", "mode": "full", "value": true, @@ -1101,8 +1101,8 @@ func TestApplyParamOverrideReturnError(t *testing.T) { }, }, } - ctx := map[string]interface{}{ - "retry": map[string]interface{}{ + ctx := map[string]any{ + "retry": map[string]any{ "index": 1, "is_retry": true, }, @@ -1144,9 +1144,9 @@ func TestApplyParamOverridePruneObjectsByTypeString(t *testing.T) { ]} ] }`) - override := map[string]interface{}{ - "operations": []interface{}{ - map[string]interface{}{ + override := map[string]any{ + "operations": []any{ + map[string]any{ "mode": "prune_objects", "value": "redacted_thinking", }, @@ -1178,13 +1178,13 @@ func TestApplyParamOverridePruneObjectsWhereAndPath(t *testing.T) { "a":{"items":[{"type":"redacted_thinking","id":1},{"type":"output_text","id":2}]}, "b":{"items":[{"type":"redacted_thinking","id":3},{"type":"output_text","id":4}]} }`) - override := map[string]interface{}{ - "operations": []interface{}{ - map[string]interface{}{ + override := map[string]any{ + "operations": []any{ + map[string]any{ "path": "a", "mode": "prune_objects", - "value": map[string]interface{}{ - "where": map[string]interface{}{ + "value": map[string]any{ + "where": map[string]any{ "type": "redacted_thinking", }, }, @@ -1204,9 +1204,9 @@ func TestApplyParamOverridePruneObjectsWhereAndPath(t *testing.T) { func TestApplyParamOverrideNormalizeThinkingSignatureUnsupported(t *testing.T) { input := []byte(`{"items":[{"type":"redacted_thinking"}]}`) - override := map[string]interface{}{ - "operations": []interface{}{ - map[string]interface{}{ + override := map[string]any{ + "operations": []any{ + map[string]any{ "mode": "normalize_thinking_signature", }, }, @@ -1230,20 +1230,20 @@ func TestApplyParamOverrideConditionFromRetryAndLastErrorContext(t *testing.T) { ctx := BuildParamOverrideContext(info) input := []byte(`{"temperature":0.7}`) - override := map[string]interface{}{ - "operations": []interface{}{ - map[string]interface{}{ + override := map[string]any{ + "operations": []any{ + map[string]any{ "path": "temperature", "mode": "set", "value": 0.1, "logic": "AND", - "conditions": []interface{}{ - map[string]interface{}{ + "conditions": []any{ + map[string]any{ "path": "is_retry", "mode": "full", "value": true, }, - map[string]interface{}{ + map[string]any{ "path": "last_error.code", "mode": "contains", "value": "thought_signature", @@ -1261,20 +1261,20 @@ func TestApplyParamOverrideConditionFromRetryAndLastErrorContext(t *testing.T) { } func TestApplyParamOverrideConditionByUserAndGPTModel(t *testing.T) { - paramOverride := map[string]interface{}{ - "operations": []interface{}{ - map[string]interface{}{ + paramOverride := map[string]any{ + "operations": []any{ + map[string]any{ "path": "service_tier", "mode": "set", "value": "priority", "logic": "AND", - "conditions": []interface{}{ - map[string]interface{}{ + "conditions": []any{ + map[string]any{ "path": "user_id", "mode": "full", "value": 1, }, - map[string]interface{}{ + map[string]any{ "path": "upstream_model", "mode": "contains", "value": "gpt", @@ -1336,25 +1336,25 @@ func TestApplyParamOverrideConditionByGroupContext(t *testing.T) { UsingGroup: "priority-route", } ctx := BuildParamOverrideContext(info) - paramOverride := map[string]interface{}{ - "operations": []interface{}{ - map[string]interface{}{ + paramOverride := map[string]any{ + "operations": []any{ + map[string]any{ "path": "service_tier", "mode": "set", "value": "priority", "logic": "AND", - "conditions": []interface{}{ - map[string]interface{}{ + "conditions": []any{ + map[string]any{ "path": "user_group", "mode": "full", "value": "vip", }, - map[string]interface{}{ + map[string]any{ "path": "token_group", "mode": "full", "value": "premium", }, - map[string]interface{}{ + map[string]any{ "path": "using_group", "mode": "full", "value": "priority-route", @@ -1372,14 +1372,14 @@ func TestApplyParamOverrideConditionByGroupContext(t *testing.T) { func TestApplyParamOverrideConditionFromRequestHeaders(t *testing.T) { input := []byte(`{"temperature":0.7}`) - override := map[string]interface{}{ - "operations": []interface{}{ - map[string]interface{}{ + override := map[string]any{ + "operations": []any{ + map[string]any{ "path": "temperature", "mode": "set", "value": 0.1, - "conditions": []interface{}{ - map[string]interface{}{ + "conditions": []any{ + map[string]any{ "path": "request_headers.authorization", "mode": "contains", "value": "Bearer ", @@ -1388,8 +1388,8 @@ func TestApplyParamOverrideConditionFromRequestHeaders(t *testing.T) { }, }, } - ctx := map[string]interface{}{ - "request_headers": map[string]interface{}{ + ctx := map[string]any{ + "request_headers": map[string]any{ "authorization": "Bearer token-123", }, } @@ -1403,19 +1403,19 @@ func TestApplyParamOverrideConditionFromRequestHeaders(t *testing.T) { func TestApplyParamOverrideSetHeaderAndUseInLaterCondition(t *testing.T) { input := []byte(`{"temperature":0.7}`) - override := map[string]interface{}{ - "operations": []interface{}{ - map[string]interface{}{ + override := map[string]any{ + "operations": []any{ + map[string]any{ "mode": "set_header", "path": "X-Debug-Mode", "value": "enabled", }, - map[string]interface{}{ + map[string]any{ "path": "temperature", "mode": "set", "value": 0.1, - "conditions": []interface{}{ - map[string]interface{}{ + "conditions": []any{ + map[string]any{ "path": "header_override.x-debug-mode", "mode": "full", "value": "enabled", @@ -1434,19 +1434,19 @@ func TestApplyParamOverrideSetHeaderAndUseInLaterCondition(t *testing.T) { func TestApplyParamOverrideCopyHeaderFromRequestHeaders(t *testing.T) { input := []byte(`{"temperature":0.7}`) - override := map[string]interface{}{ - "operations": []interface{}{ - map[string]interface{}{ + override := map[string]any{ + "operations": []any{ + map[string]any{ "mode": "copy_header", "from": "Authorization", "to": "X-Upstream-Auth", }, - map[string]interface{}{ + map[string]any{ "path": "temperature", "mode": "set", "value": 0.1, - "conditions": []interface{}{ - map[string]interface{}{ + "conditions": []any{ + map[string]any{ "path": "header_override.x-upstream-auth", "mode": "contains", "value": "Bearer ", @@ -1455,8 +1455,8 @@ func TestApplyParamOverrideCopyHeaderFromRequestHeaders(t *testing.T) { }, }, } - ctx := map[string]interface{}{ - "request_headers": map[string]interface{}{ + ctx := map[string]any{ + "request_headers": map[string]any{ "authorization": "Bearer token-123", }, } @@ -1470,16 +1470,16 @@ func TestApplyParamOverrideCopyHeaderFromRequestHeaders(t *testing.T) { func TestApplyParamOverridePassHeadersSkipsMissingHeaders(t *testing.T) { input := []byte(`{"temperature":0.7}`) - override := map[string]interface{}{ - "operations": []interface{}{ - map[string]interface{}{ + override := map[string]any{ + "operations": []any{ + map[string]any{ "mode": "pass_headers", - "value": []interface{}{"X-Codex-Beta-Features", "Session_id"}, + "value": []any{"X-Codex-Beta-Features", "Session_id"}, }, }, } - ctx := map[string]interface{}{ - "request_headers": map[string]interface{}{ + ctx := map[string]any{ + "request_headers": map[string]any{ "session_id": "sess-123", }, } @@ -1490,7 +1490,7 @@ func TestApplyParamOverridePassHeadersSkipsMissingHeaders(t *testing.T) { } assertJSONEqual(t, `{"temperature":0.7}`, string(out)) - headers, ok := ctx["header_override"].(map[string]interface{}) + headers, ok := ctx["header_override"].(map[string]any) if !ok { t.Fatalf("expected header_override context map") } @@ -1504,17 +1504,17 @@ func TestApplyParamOverridePassHeadersSkipsMissingHeaders(t *testing.T) { func TestApplyParamOverrideCopyHeaderSkipsMissingSource(t *testing.T) { input := []byte(`{"temperature":0.7}`) - override := map[string]interface{}{ - "operations": []interface{}{ - map[string]interface{}{ + override := map[string]any{ + "operations": []any{ + map[string]any{ "mode": "copy_header", "from": "X-Missing-Header", "to": "X-Upstream-Auth", }, }, } - ctx := map[string]interface{}{ - "request_headers": map[string]interface{}{ + ctx := map[string]any{ + "request_headers": map[string]any{ "authorization": "Bearer token-123", }, } @@ -1525,7 +1525,7 @@ func TestApplyParamOverrideCopyHeaderSkipsMissingSource(t *testing.T) { } assertJSONEqual(t, `{"temperature":0.7}`, string(out)) - headers, ok := ctx["header_override"].(map[string]interface{}) + headers, ok := ctx["header_override"].(map[string]any) if !ok { return } @@ -1536,17 +1536,17 @@ func TestApplyParamOverrideCopyHeaderSkipsMissingSource(t *testing.T) { func TestApplyParamOverrideMoveHeaderSkipsMissingSource(t *testing.T) { input := []byte(`{"temperature":0.7}`) - override := map[string]interface{}{ - "operations": []interface{}{ - map[string]interface{}{ + override := map[string]any{ + "operations": []any{ + map[string]any{ "mode": "move_header", "from": "X-Missing-Header", "to": "X-Upstream-Auth", }, }, } - ctx := map[string]interface{}{ - "request_headers": map[string]interface{}{ + ctx := map[string]any{ + "request_headers": map[string]any{ "authorization": "Bearer token-123", }, } @@ -1557,7 +1557,7 @@ func TestApplyParamOverrideMoveHeaderSkipsMissingSource(t *testing.T) { } assertJSONEqual(t, `{"temperature":0.7}`, string(out)) - headers, ok := ctx["header_override"].(map[string]interface{}) + headers, ok := ctx["header_override"].(map[string]any) if !ok { return } @@ -1568,17 +1568,17 @@ func TestApplyParamOverrideMoveHeaderSkipsMissingSource(t *testing.T) { func TestApplyParamOverrideSyncFieldsHeaderToJSON(t *testing.T) { input := []byte(`{"model":"gpt-4"}`) - override := map[string]interface{}{ - "operations": []interface{}{ - map[string]interface{}{ + override := map[string]any{ + "operations": []any{ + map[string]any{ "mode": "sync_fields", "from": "header:session_id", "to": "json:prompt_cache_key", }, }, } - ctx := map[string]interface{}{ - "request_headers": map[string]interface{}{ + ctx := map[string]any{ + "request_headers": map[string]any{ "session_id": "sess-123", }, } @@ -1592,16 +1592,16 @@ func TestApplyParamOverrideSyncFieldsHeaderToJSON(t *testing.T) { func TestApplyParamOverrideSyncFieldsJSONToHeader(t *testing.T) { input := []byte(`{"model":"gpt-4","prompt_cache_key":"cache-abc"}`) - override := map[string]interface{}{ - "operations": []interface{}{ - map[string]interface{}{ + override := map[string]any{ + "operations": []any{ + map[string]any{ "mode": "sync_fields", "from": "header:session_id", "to": "json:prompt_cache_key", }, }, } - ctx := map[string]interface{}{} + ctx := map[string]any{} out, err := ApplyParamOverride(input, override, ctx) if err != nil { @@ -1609,7 +1609,7 @@ func TestApplyParamOverrideSyncFieldsJSONToHeader(t *testing.T) { } assertJSONEqual(t, `{"model":"gpt-4","prompt_cache_key":"cache-abc"}`, string(out)) - headers, ok := ctx["header_override"].(map[string]interface{}) + headers, ok := ctx["header_override"].(map[string]any) if !ok { t.Fatalf("expected header_override context map") } @@ -1620,17 +1620,17 @@ func TestApplyParamOverrideSyncFieldsJSONToHeader(t *testing.T) { func TestApplyParamOverrideSyncFieldsNoChangeWhenBothExist(t *testing.T) { input := []byte(`{"model":"gpt-4","prompt_cache_key":"cache-body"}`) - override := map[string]interface{}{ - "operations": []interface{}{ - map[string]interface{}{ + override := map[string]any{ + "operations": []any{ + map[string]any{ "mode": "sync_fields", "from": "header:session_id", "to": "json:prompt_cache_key", }, }, } - ctx := map[string]interface{}{ - "request_headers": map[string]interface{}{ + ctx := map[string]any{ + "request_headers": map[string]any{ "session_id": "cache-header", }, } @@ -1641,7 +1641,7 @@ func TestApplyParamOverrideSyncFieldsNoChangeWhenBothExist(t *testing.T) { } assertJSONEqual(t, `{"model":"gpt-4","prompt_cache_key":"cache-body"}`, string(out)) - headers, _ := ctx["header_override"].(map[string]interface{}) + headers, _ := ctx["header_override"].(map[string]any) if headers != nil { if _, exists := headers["session_id"]; exists { t.Fatalf("expected no override when both sides already have value") @@ -1651,9 +1651,9 @@ func TestApplyParamOverrideSyncFieldsNoChangeWhenBothExist(t *testing.T) { func TestApplyParamOverrideSyncFieldsInvalidTarget(t *testing.T) { input := []byte(`{"model":"gpt-4"}`) - override := map[string]interface{}{ - "operations": []interface{}{ - map[string]interface{}{ + override := map[string]any{ + "operations": []any{ + map[string]any{ "mode": "sync_fields", "from": "foo:session_id", "to": "json:prompt_cache_key", @@ -1669,9 +1669,9 @@ func TestApplyParamOverrideSyncFieldsInvalidTarget(t *testing.T) { func TestApplyParamOverrideSetHeaderKeepOrigin(t *testing.T) { input := []byte(`{"temperature":0.7}`) - override := map[string]interface{}{ - "operations": []interface{}{ - map[string]interface{}{ + override := map[string]any{ + "operations": []any{ + map[string]any{ "mode": "set_header", "path": "X-Feature-Flag", "value": "new-value", @@ -1679,8 +1679,8 @@ func TestApplyParamOverrideSetHeaderKeepOrigin(t *testing.T) { }, }, } - ctx := map[string]interface{}{ - "header_override": map[string]interface{}{ + ctx := map[string]any{ + "header_override": map[string]any{ "x-feature-flag": "legacy-value", }, } @@ -1689,7 +1689,7 @@ func TestApplyParamOverrideSetHeaderKeepOrigin(t *testing.T) { if err != nil { t.Fatalf("ApplyParamOverride returned error: %v", err) } - headers, ok := ctx["header_override"].(map[string]interface{}) + headers, ok := ctx["header_override"].(map[string]any) if !ok { t.Fatalf("expected header_override context map") } @@ -1700,20 +1700,20 @@ func TestApplyParamOverrideSetHeaderKeepOrigin(t *testing.T) { func TestApplyParamOverrideSetHeaderMapRewritesCommaSeparatedHeader(t *testing.T) { input := []byte(`{"temperature":0.7}`) - override := map[string]interface{}{ - "operations": []interface{}{ - map[string]interface{}{ + override := map[string]any{ + "operations": []any{ + map[string]any{ "mode": "set_header", "path": "anthropic-beta", - "value": map[string]interface{}{ + "value": map[string]any{ "advanced-tool-use-2025-11-20": nil, "computer-use-2025-01-24": "computer-use-2025-01-24", }, }, }, } - ctx := map[string]interface{}{ - "request_headers": map[string]interface{}{ + ctx := map[string]any{ + "request_headers": map[string]any{ "anthropic-beta": "advanced-tool-use-2025-11-20, computer-use-2025-01-24", }, } @@ -1723,7 +1723,7 @@ func TestApplyParamOverrideSetHeaderMapRewritesCommaSeparatedHeader(t *testing.T t.Fatalf("ApplyParamOverride returned error: %v", err) } - headers, ok := ctx["header_override"].(map[string]interface{}) + headers, ok := ctx["header_override"].(map[string]any) if !ok { t.Fatalf("expected header_override context map") } @@ -1734,20 +1734,20 @@ func TestApplyParamOverrideSetHeaderMapRewritesCommaSeparatedHeader(t *testing.T func TestApplyParamOverrideSetHeaderMapDeleteWholeHeaderWhenAllTokensCleared(t *testing.T) { input := []byte(`{"temperature":0.7}`) - override := map[string]interface{}{ - "operations": []interface{}{ - map[string]interface{}{ + override := map[string]any{ + "operations": []any{ + map[string]any{ "mode": "set_header", "path": "anthropic-beta", - "value": map[string]interface{}{ + "value": map[string]any{ "advanced-tool-use-2025-11-20": nil, "computer-use-2025-01-24": nil, }, }, }, } - ctx := map[string]interface{}{ - "header_override": map[string]interface{}{ + ctx := map[string]any{ + "header_override": map[string]any{ "anthropic-beta": "advanced-tool-use-2025-11-20,computer-use-2025-01-24", }, } @@ -1757,7 +1757,7 @@ func TestApplyParamOverrideSetHeaderMapDeleteWholeHeaderWhenAllTokensCleared(t * t.Fatalf("ApplyParamOverride returned error: %v", err) } - headers, ok := ctx["header_override"].(map[string]interface{}) + headers, ok := ctx["header_override"].(map[string]any) if !ok { t.Fatalf("expected header_override context map") } @@ -1768,19 +1768,19 @@ func TestApplyParamOverrideSetHeaderMapDeleteWholeHeaderWhenAllTokensCleared(t * func TestApplyParamOverrideSetHeaderMapAppendsTokens(t *testing.T) { input := []byte(`{"temperature":0.7}`) - override := map[string]interface{}{ - "operations": []interface{}{ - map[string]interface{}{ + override := map[string]any{ + "operations": []any{ + map[string]any{ "mode": "set_header", "path": "anthropic-beta", - "value": map[string]interface{}{ - "$append": []interface{}{"context-1m-2025-08-07", "computer-use-2025-01-24"}, + "value": map[string]any{ + "$append": []any{"context-1m-2025-08-07", "computer-use-2025-01-24"}, }, }, }, } - ctx := map[string]interface{}{ - "header_override": map[string]interface{}{ + ctx := map[string]any{ + "header_override": map[string]any{ "anthropic-beta": "computer-use-2025-01-24", }, } @@ -1791,7 +1791,7 @@ func TestApplyParamOverrideSetHeaderMapAppendsTokens(t *testing.T) { } assertJSONEqual(t, `{"temperature":0.7}`, string(out)) - headers, ok := ctx["header_override"].(map[string]interface{}) + headers, ok := ctx["header_override"].(map[string]any) if !ok { t.Fatalf("expected header_override context map") } @@ -1802,26 +1802,26 @@ func TestApplyParamOverrideSetHeaderMapAppendsTokens(t *testing.T) { func TestApplyParamOverrideSetHeaderMapAppendsTokensWhenHeaderMissing(t *testing.T) { input := []byte(`{"temperature":0.7}`) - override := map[string]interface{}{ - "operations": []interface{}{ - map[string]interface{}{ + override := map[string]any{ + "operations": []any{ + map[string]any{ "mode": "set_header", "path": "anthropic-beta", - "value": map[string]interface{}{ - "$append": []interface{}{"context-1m-2025-08-07", "computer-use-2025-01-24"}, + "value": map[string]any{ + "$append": []any{"context-1m-2025-08-07", "computer-use-2025-01-24"}, }, }, }, } - ctx := map[string]interface{}{} + ctx := map[string]any{} out, err := ApplyParamOverride(input, override, ctx) if err != nil { t.Fatalf("ApplyParamOverride returned error: %v", err) } assertJSONEqual(t, `{"temperature":0.7}`, string(out)) - headers, ok := ctx["header_override"].(map[string]interface{}) + headers, ok := ctx["header_override"].(map[string]any) if !ok { t.Fatalf("expected header_override context map") } @@ -1832,21 +1832,21 @@ func TestApplyParamOverrideSetHeaderMapAppendsTokensWhenHeaderMissing(t *testing func TestApplyParamOverrideSetHeaderMapKeepOnlyDeclaredDropsUndeclaredTokens(t *testing.T) { input := []byte(`{"temperature":0.7}`) - override := map[string]interface{}{ - "operations": []interface{}{ - map[string]interface{}{ + override := map[string]any{ + "operations": []any{ + map[string]any{ "mode": "set_header", "path": "anthropic-beta", - "value": map[string]interface{}{ + "value": map[string]any{ "computer-use-2025-01-24": "computer-use-2025-01-24", - "$append": []interface{}{"context-1m-2025-08-07"}, + "$append": []any{"context-1m-2025-08-07"}, "$keep_only_declared": true, }, }, }, } - ctx := map[string]interface{}{ - "header_override": map[string]interface{}{ + ctx := map[string]any{ + "header_override": map[string]any{ "anthropic-beta": "advanced-tool-use-2025-11-20,computer-use-2025-01-24", }, } @@ -1857,7 +1857,7 @@ func TestApplyParamOverrideSetHeaderMapKeepOnlyDeclaredDropsUndeclaredTokens(t * } assertJSONEqual(t, `{"temperature":0.7}`, string(out)) - headers, ok := ctx["header_override"].(map[string]interface{}) + headers, ok := ctx["header_override"].(map[string]any) if !ok { t.Fatalf("expected header_override context map") } @@ -1868,20 +1868,20 @@ func TestApplyParamOverrideSetHeaderMapKeepOnlyDeclaredDropsUndeclaredTokens(t * func TestApplyParamOverrideSetHeaderMapKeepOnlyDeclaredDeletesHeaderWhenNothingDeclaredMatches(t *testing.T) { input := []byte(`{"temperature":0.7}`) - override := map[string]interface{}{ - "operations": []interface{}{ - map[string]interface{}{ + override := map[string]any{ + "operations": []any{ + map[string]any{ "mode": "set_header", "path": "anthropic-beta", - "value": map[string]interface{}{ + "value": map[string]any{ "computer-use-2025-01-24": "computer-use-2025-01-24", "$keep_only_declared": true, }, }, }, } - ctx := map[string]interface{}{ - "header_override": map[string]interface{}{ + ctx := map[string]any{ + "header_override": map[string]any{ "anthropic-beta": "advanced-tool-use-2025-11-20", }, } @@ -1892,7 +1892,7 @@ func TestApplyParamOverrideSetHeaderMapKeepOnlyDeclaredDeletesHeaderWhenNothingD } assertJSONEqual(t, `{"temperature":0.7}`, string(out)) - headers, ok := ctx["header_override"].(map[string]interface{}) + headers, ok := ctx["header_override"].(map[string]any) if !ok { t.Fatalf("expected header_override context map") } @@ -1903,23 +1903,23 @@ func TestApplyParamOverrideSetHeaderMapKeepOnlyDeclaredDeletesHeaderWhenNothingD func TestApplyParamOverrideConditionsObjectShorthand(t *testing.T) { input := []byte(`{"temperature":0.7}`) - override := map[string]interface{}{ - "operations": []interface{}{ - map[string]interface{}{ + override := map[string]any{ + "operations": []any{ + map[string]any{ "path": "temperature", "mode": "set", "value": 0.1, "logic": "AND", - "conditions": map[string]interface{}{ + "conditions": map[string]any{ "is_retry": true, "last_error.status_code": 400.0, }, }, }, } - ctx := map[string]interface{}{ + ctx := map[string]any{ "is_retry": true, - "last_error": map[string]interface{}{ + "last_error": map[string]any{ "status_code": 400.0, }, } @@ -1934,20 +1934,20 @@ func TestApplyParamOverrideConditionsObjectShorthand(t *testing.T) { func TestApplyParamOverrideWithRelayInfoSyncRuntimeHeaders(t *testing.T) { info := &RelayInfo{ ChannelMeta: &ChannelMeta{ - ParamOverride: map[string]interface{}{ - "operations": []interface{}{ - map[string]interface{}{ + ParamOverride: map[string]any{ + "operations": []any{ + map[string]any{ "mode": "set_header", "path": "X-Injected-By-Param-Override", "value": "enabled", }, - map[string]interface{}{ + map[string]any{ "mode": "delete_header", "path": "X-Delete-Me", }, }, }, - HeadersOverride: map[string]interface{}{ + HeadersOverride: map[string]any{ "X-Delete-Me": "legacy", "X-Keep-Me": "keep", }, @@ -1981,16 +1981,16 @@ func TestApplyParamOverrideWithRelayInfoMixedLegacyAndOperations(t *testing.T) { "Originator": "Codex CLI", }, ChannelMeta: &ChannelMeta{ - ParamOverride: map[string]interface{}{ + ParamOverride: map[string]any{ "temperature": 0.2, - "operations": []interface{}{ - map[string]interface{}{ + "operations": []any{ + map[string]any{ "mode": "pass_headers", - "value": []interface{}{"Originator"}, + "value": []any{"Originator"}, }, }, }, - HeadersOverride: map[string]interface{}{ + HeadersOverride: map[string]any{ "X-Static": "legacy-static", }, }, @@ -2016,21 +2016,21 @@ func TestApplyParamOverrideWithRelayInfoMixedLegacyAndOperations(t *testing.T) { func TestApplyParamOverrideWithRelayInfoMoveAndCopyHeaders(t *testing.T) { info := &RelayInfo{ ChannelMeta: &ChannelMeta{ - ParamOverride: map[string]interface{}{ - "operations": []interface{}{ - map[string]interface{}{ + ParamOverride: map[string]any{ + "operations": []any{ + map[string]any{ "mode": "move_header", "from": "X-Legacy-Trace", "to": "X-Trace", }, - map[string]interface{}{ + map[string]any{ "mode": "copy_header", "from": "X-Trace", "to": "X-Trace-Backup", }, }, }, - HeadersOverride: map[string]interface{}{ + HeadersOverride: map[string]any{ "X-Legacy-Trace": "trace-123", }, }, @@ -2055,19 +2055,19 @@ func TestApplyParamOverrideWithRelayInfoMoveAndCopyHeaders(t *testing.T) { func TestApplyParamOverrideWithRelayInfoSetHeaderMapRewritesAnthropicBeta(t *testing.T) { info := &RelayInfo{ ChannelMeta: &ChannelMeta{ - ParamOverride: map[string]interface{}{ - "operations": []interface{}{ - map[string]interface{}{ + ParamOverride: map[string]any{ + "operations": []any{ + map[string]any{ "mode": "set_header", "path": "anthropic-beta", - "value": map[string]interface{}{ + "value": map[string]any{ "advanced-tool-use-2025-11-20": nil, "computer-use-2025-01-24": "computer-use-2025-01-24", }, }, }, }, - HeadersOverride: map[string]interface{}{ + HeadersOverride: map[string]any{ "anthropic-beta": "advanced-tool-use-2025-11-20, computer-use-2025-01-24", }, }, @@ -2089,11 +2089,11 @@ func TestApplyParamOverrideWithRelayInfoSetHeaderMapRewritesAnthropicBeta(t *tes func TestGetEffectiveHeaderOverrideUsesRuntimeOverrideAsFinalResult(t *testing.T) { info := &RelayInfo{ UseRuntimeHeadersOverride: true, - RuntimeHeadersOverride: map[string]interface{}{ + RuntimeHeadersOverride: map[string]any{ "x-runtime": "runtime-only", }, ChannelMeta: &ChannelMeta{ - HeadersOverride: map[string]interface{}{ + HeadersOverride: map[string]any{ "X-Static": "static-value", "X-Deleted": "should-not-exist", }, @@ -2217,19 +2217,19 @@ func TestApplyParamOverrideWithRelayInfoRecordsOperationAuditInDebugMode(t *test info := &RelayInfo{ ChannelMeta: &ChannelMeta{ - ParamOverride: map[string]interface{}{ - "operations": []interface{}{ - map[string]interface{}{ + ParamOverride: map[string]any{ + "operations": []any{ + map[string]any{ "mode": "copy", "from": "metadata.target_model", "to": "model", }, - map[string]interface{}{ + map[string]any{ "mode": "set", "path": "service_tier", "value": "flex", }, - map[string]interface{}{ + map[string]any{ "mode": "set", "path": "temperature", "value": 0.1, @@ -2273,14 +2273,14 @@ func TestApplyParamOverrideWithRelayInfoRecordsOnlyKeyOperationsWhenDebugDisable info := &RelayInfo{ ChannelMeta: &ChannelMeta{ - ParamOverride: map[string]interface{}{ - "operations": []interface{}{ - map[string]interface{}{ + ParamOverride: map[string]any{ + "operations": []any{ + map[string]any{ "mode": "copy", "from": "metadata.target_model", "to": "model", }, - map[string]interface{}{ + map[string]any{ "mode": "set", "path": "temperature", "value": 0.1, @@ -2316,35 +2316,35 @@ func TestApplyParamOverrideWithRelayInfoRecordsConversationBodyOperationsWhenDeb info := &RelayInfo{ ChannelMeta: &ChannelMeta{ - ParamOverride: map[string]interface{}{ - "operations": []interface{}{ - map[string]interface{}{ + ParamOverride: map[string]any{ + "operations": []any{ + map[string]any{ "mode": "replace", "path": "messages.0.content", "from": "hello", "to": "hi", }, - map[string]interface{}{ + map[string]any{ "mode": "set", "path": "input.0.content.0.text", "value": "rewritten response input", }, - map[string]interface{}{ + map[string]any{ "mode": "set", "path": "instructions", "value": "new instruction", }, - map[string]interface{}{ + map[string]any{ "mode": "append", "path": "contents.0.parts", - "value": map[string]interface{}{"text": "new gemini part"}, + "value": map[string]any{"text": "new gemini part"}, }, - map[string]interface{}{ + map[string]any{ "mode": "copy", "from": "system", "to": "metadata.system_copy", }, - map[string]interface{}{ + map[string]any{ "mode": "set", "path": "temperature", "value": 0.1, @@ -2399,8 +2399,8 @@ func TestShouldAuditParamPathUsesFieldBoundaryPrefixMatching(t *testing.T) { func assertJSONEqual(t *testing.T, want, got string) { t.Helper() - var wantObj interface{} - var gotObj interface{} + var wantObj any + var gotObj any if err := json.Unmarshal([]byte(want), &wantObj); err != nil { t.Fatalf("failed to unmarshal want JSON: %v", err) @@ -2426,7 +2426,7 @@ func TestApplyParamOverrideWithRelayInfoSynchronizesReasoningEffort(t *testing.T relayFormat types.RelayFormat initialEffort string input string - operation map[string]interface{} + operation map[string]any expected string }{ { @@ -2434,7 +2434,7 @@ func TestApplyParamOverrideWithRelayInfoSynchronizesReasoningEffort(t *testing.T relayFormat: types.RelayFormatOpenAIResponses, initialEffort: "high", input: `{"reasoning":{"effort":"high"}}`, - operation: map[string]interface{}{"mode": "set", "path": "reasoning.effort", "value": "max"}, + operation: map[string]any{"mode": "set", "path": "reasoning.effort", "value": "max"}, expected: "max", }, { @@ -2442,7 +2442,7 @@ func TestApplyParamOverrideWithRelayInfoSynchronizesReasoningEffort(t *testing.T relayFormat: types.RelayFormatOpenAI, initialEffort: "high", input: `{"reasoning_effort":"high"}`, - operation: map[string]interface{}{"mode": "delete", "path": "reasoning_effort"}, + operation: map[string]any{"mode": "delete", "path": "reasoning_effort"}, expected: "", }, { @@ -2450,7 +2450,7 @@ func TestApplyParamOverrideWithRelayInfoSynchronizesReasoningEffort(t *testing.T relayFormat: types.RelayFormatOpenAI, initialEffort: "medium", input: `{"reasoning":{"effort":"medium"}}`, - operation: map[string]interface{}{"mode": "set", "path": "reasoning.effort", "value": "xhigh"}, + operation: map[string]any{"mode": "set", "path": "reasoning.effort", "value": "xhigh"}, expected: "xhigh", }, { @@ -2458,7 +2458,7 @@ func TestApplyParamOverrideWithRelayInfoSynchronizesReasoningEffort(t *testing.T relayFormat: types.RelayFormatClaude, initialEffort: "high", input: `{"output_config":{"effort":"high"}}`, - operation: map[string]interface{}{"mode": "set", "path": "output_config.effort", "value": "max"}, + operation: map[string]any{"mode": "set", "path": "output_config.effort", "value": "max"}, expected: "max", }, { @@ -2466,7 +2466,7 @@ func TestApplyParamOverrideWithRelayInfoSynchronizesReasoningEffort(t *testing.T relayFormat: types.RelayFormatGemini, initialEffort: "medium", input: `{"generationConfig":{"thinkingConfig":{"thinkingLevel":"medium"}}}`, - operation: map[string]interface{}{"mode": "set", "path": "generationConfig.thinkingConfig.thinkingLevel", "value": "high"}, + operation: map[string]any{"mode": "set", "path": "generationConfig.thinkingConfig.thinkingLevel", "value": "high"}, expected: "high", }, { @@ -2474,7 +2474,7 @@ func TestApplyParamOverrideWithRelayInfoSynchronizesReasoningEffort(t *testing.T relayFormat: types.RelayFormatOpenAIResponses, initialEffort: "high", input: `{"reasoning":{"effort":"high"}}`, - operation: map[string]interface{}{"mode": "set", "path": "reasoning.effort", "value": 42}, + operation: map[string]any{"mode": "set", "path": "reasoning.effort", "value": 42}, expected: "", }, { @@ -2482,7 +2482,7 @@ func TestApplyParamOverrideWithRelayInfoSynchronizesReasoningEffort(t *testing.T relayFormat: types.RelayFormatClaude, initialEffort: "high", input: `{"thinking":{"type":"adaptive"},"max_tokens":4096}`, - operation: map[string]interface{}{"mode": "set", "path": "max_tokens", "value": 8192}, + operation: map[string]any{"mode": "set", "path": "max_tokens", "value": 8192}, expected: "high", }, } @@ -2492,8 +2492,8 @@ func TestApplyParamOverrideWithRelayInfoSynchronizesReasoningEffort(t *testing.T info := &RelayInfo{ RelayFormat: tt.relayFormat, ReasoningEffort: tt.initialEffort, - ChannelMeta: &ChannelMeta{ParamOverride: map[string]interface{}{ - "operations": []interface{}{tt.operation}, + ChannelMeta: &ChannelMeta{ParamOverride: map[string]any{ + "operations": []any{tt.operation}, }}, } @@ -2512,9 +2512,9 @@ func TestReasoningEffortOverrideIsAuditedWithoutDebugMode(t *testing.T) { }) info := &RelayInfo{ RelayFormat: types.RelayFormatOpenAIResponses, - ChannelMeta: &ChannelMeta{ParamOverride: map[string]interface{}{ - "operations": []interface{}{ - map[string]interface{}{"mode": "set", "path": "reasoning.effort", "value": "max"}, + ChannelMeta: &ChannelMeta{ParamOverride: map[string]any{ + "operations": []any{ + map[string]any{"mode": "set", "path": "reasoning.effort", "value": "max"}, }, }}, } diff --git a/relay/common/relay_info.go b/relay/common/relay_info.go index e02559754c..463032d9d8 100644 --- a/relay/common/relay_info.go +++ b/relay/common/relay_info.go @@ -67,8 +67,8 @@ type ChannelMeta struct { ApiKey string Organization string ChannelCreateTime int64 - ParamOverride map[string]interface{} - HeadersOverride map[string]interface{} + ParamOverride map[string]any + HeadersOverride map[string]any ChannelSetting dto.ChannelSettings ChannelOtherSettings dto.ChannelOtherSettings UpstreamModelName string @@ -160,7 +160,7 @@ type RelayInfo struct { IsChannelTest bool // channel test request RetryIndex int LastError *types.NewAPIError - RuntimeHeadersOverride map[string]interface{} + RuntimeHeadersOverride map[string]any UseRuntimeHeadersOverride bool ParamOverrideAudit []string @@ -938,16 +938,16 @@ type TaskRelayInfo struct { } type TaskSubmitReq struct { - Prompt string `json:"prompt"` - Model string `json:"model,omitempty"` - Mode string `json:"mode,omitempty"` - Image string `json:"image,omitempty"` - Images []string `json:"images,omitempty"` - Size string `json:"size,omitempty"` - Duration int `json:"duration,omitempty"` - Seconds string `json:"seconds,omitempty"` - InputReference string `json:"input_reference,omitempty"` - Metadata map[string]interface{} `json:"metadata,omitempty"` + Prompt string `json:"prompt"` + Model string `json:"model,omitempty"` + Mode string `json:"mode,omitempty"` + Image string `json:"image,omitempty"` + Images []string `json:"images,omitempty"` + Size string `json:"size,omitempty"` + Duration int `json:"duration,omitempty"` + Seconds string `json:"seconds,omitempty"` + InputReference string `json:"input_reference,omitempty"` + Metadata map[string]any `json:"metadata,omitempty"` } func (t *TaskSubmitReq) GetPrompt() string { @@ -989,14 +989,14 @@ func (t *TaskSubmitReq) UnmarshalJSON(data []byte) error { if len(aux.Metadata) > 0 { var metadataStr string if err := common.Unmarshal(aux.Metadata, &metadataStr); err == nil && metadataStr != "" { - var metadataObj map[string]interface{} + var metadataObj map[string]any if err := common.Unmarshal([]byte(metadataStr), &metadataObj); err == nil { t.Metadata = metadataObj return nil } } - var metadataObj map[string]interface{} + var metadataObj map[string]any if err := common.Unmarshal(aux.Metadata, &metadataObj); err == nil { t.Metadata = metadataObj } @@ -1055,7 +1055,7 @@ func RemoveDisabledFields(jsonData []byte, channelOtherSettings dto.ChannelOther return jsonData, nil } - var data map[string]interface{} + var data map[string]any if err := common.Unmarshal(jsonData, &data); err != nil { common.SysError("RemoveDisabledFields Unmarshal error :" + err.Error()) return jsonData, nil @@ -1099,7 +1099,7 @@ func RemoveDisabledFields(jsonData []byte, channelOtherSettings dto.ChannelOther // 默认移除 stream_options.include_obfuscation,除非明确允许(避免关闭响应流混淆保护) if !channelOtherSettings.AllowIncludeObfuscation { if streamOptionsAny, exists := data["stream_options"]; exists { - if streamOptions, ok := streamOptionsAny.(map[string]interface{}); ok { + if streamOptions, ok := streamOptionsAny.(map[string]any); ok { if _, includeExists := streamOptions["include_obfuscation"]; includeExists { delete(streamOptions, "include_obfuscation") } @@ -1146,7 +1146,7 @@ func RemoveGeminiDisabledFields(jsonData []byte) ([]byte, error) { return jsonData, nil } - var data map[string]interface{} + var data map[string]any if err := common.Unmarshal(jsonData, &data); err != nil { common.SysError("RemoveGeminiDisabledFields Unmarshal error: " + err.Error()) return jsonData, nil @@ -1154,18 +1154,18 @@ func RemoveGeminiDisabledFields(jsonData []byte) ([]byte, error) { // Process contents array // Handle both camelCase (functionResponse) and snake_case (function_response) - if contents, ok := data["contents"].([]interface{}); ok { + if contents, ok := data["contents"].([]any); ok { for _, content := range contents { - if contentMap, ok := content.(map[string]interface{}); ok { - if parts, ok := contentMap["parts"].([]interface{}); ok { + if contentMap, ok := content.(map[string]any); ok { + if parts, ok := contentMap["parts"].([]any); ok { for _, part := range parts { - if partMap, ok := part.(map[string]interface{}); ok { + if partMap, ok := part.(map[string]any); ok { // Check functionResponse (camelCase) - if funcResp, ok := partMap["functionResponse"].(map[string]interface{}); ok { + if funcResp, ok := partMap["functionResponse"].(map[string]any); ok { delete(funcResp, "id") } // Check function_response (snake_case) - if funcResp, ok := partMap["function_response"].(map[string]interface{}); ok { + if funcResp, ok := partMap["function_response"].(map[string]any); ok { delete(funcResp, "id") } } diff --git a/relay/common/relay_utils.go b/relay/common/relay_utils.go index a0c623ef96..6150509960 100644 --- a/relay/common/relay_utils.go +++ b/relay/common/relay_utils.go @@ -169,7 +169,7 @@ func validateMultipartTaskRequest(c *gin.Context, info *RelayInfo, action string Mode: formData.Get("mode"), Image: formData.Get("image"), Size: formData.Get("size"), - Metadata: make(map[string]interface{}), + Metadata: make(map[string]any), } if durationStr := formData.Get("seconds"); durationStr != "" { diff --git a/relay/common/stream_status_test.go b/relay/common/stream_status_test.go index 4a31cb79fb..4936b3a06c 100644 --- a/relay/common/stream_status_test.go +++ b/relay/common/stream_status_test.go @@ -82,7 +82,7 @@ func TestStreamStatus_RecordError_CapAtMax(t *testing.T) { t.Parallel() s := NewStreamStatus() - for i := 0; i < 30; i++ { + for i := range 30 { s.RecordError(fmt.Sprintf("error_%d", i)) } @@ -101,7 +101,7 @@ func TestStreamStatus_RecordError_Concurrent(t *testing.T) { s := NewStreamStatus() var wg sync.WaitGroup - for i := 0; i < 100; i++ { + for i := range 100 { wg.Add(1) go func(idx int) { defer wg.Done() diff --git a/relay/common/tool_usage_test.go b/relay/common/tool_usage_test.go index c977634046..7bf8bcd9dc 100644 --- a/relay/common/tool_usage_test.go +++ b/relay/common/tool_usage_test.go @@ -303,7 +303,7 @@ func TestImageGenerationCallCounterCommitCapsAtMaxImageN(t *testing.T) { t.Parallel() counter := &ImageGenerationCallCounter{} - for i := 0; i < dto.MaxImageN+3; i++ { + for i := range dto.MaxImageN + 3 { idx := i counter.Observe(&dto.ResponsesOutput{ Type: dto.ResponsesOutputTypeImageGenerationCall, diff --git a/relay/convert_request_error_test.go b/relay/convert_request_error_test.go index 6f63240cc2..1f73376d2c 100644 --- a/relay/convert_request_error_test.go +++ b/relay/convert_request_error_test.go @@ -59,7 +59,7 @@ func TestOptInSafeToolLossRejectedAsBadRequestWithAdminDiagnostics(t *testing.T) assert.True(t, hasHostDiagnosticCode(diagnostics, "unsupported_hosted_tool")) other := service.GenerateTextOtherInfo(c, info, 1, 1, 1, 0, 0, 0, 1) - adminInfo, ok := other.Snapshot()["admin_info"].(map[string]interface{}) + adminInfo, ok := other.Snapshot()["admin_info"].(map[string]any) require.True(t, ok) require.Contains(t, adminInfo, "conversion_diagnostics") } diff --git a/relay/helper/billing_expr_request.go b/relay/helper/billing_expr_request.go index d83fc6a06b..f4fd676641 100644 --- a/relay/helper/billing_expr_request.go +++ b/relay/helper/billing_expr_request.go @@ -1,6 +1,7 @@ package helper import ( + "maps" "strings" "github.com/QuantumNous/new-api/common" @@ -14,9 +15,7 @@ func ResolveIncomingBillingExprRequestInput(c *gin.Context, info *relaycommon.Re if info != nil && info.BillingRequestInput != nil { input := cloneRequestInput(*info.BillingRequestInput) merged := cloneStringMap(info.RequestHeaders) - for k, v := range input.Headers { - merged[k] = v - } + maps.Copy(merged, input.Headers) input.Headers = merged return input, nil } diff --git a/relay/helper/common.go b/relay/helper/common.go index fa363569c4..6a37a3c23a 100644 --- a/relay/helper/common.go +++ b/relay/helper/common.go @@ -122,7 +122,7 @@ func PingData(c *gin.Context) error { return FlushWriter(c) } -func ObjectData(c *gin.Context, object interface{}) error { +func ObjectData(c *gin.Context, object any) error { if object == nil { return errors.New("object is nil") } @@ -146,7 +146,7 @@ func WssString(c *gin.Context, ws *websocket.Conn, str string) error { return ws.WriteMessage(1, []byte(str)) } -func WssObject(c *gin.Context, ws *websocket.Conn, object interface{}) error { +func WssObject(c *gin.Context, ws *websocket.Conn, object any) error { jsonData, err := common.Marshal(object) if err != nil { return fmt.Errorf("error marshalling object: %w", err) diff --git a/relay/helper/stream_scanner_test.go b/relay/helper/stream_scanner_test.go index a211951287..d6125040c3 100644 --- a/relay/helper/stream_scanner_test.go +++ b/relay/helper/stream_scanner_test.go @@ -48,7 +48,7 @@ func setupStreamTest(t *testing.T, body io.Reader) (*gin.Context, *http.Response func buildSSEBody(n int) string { var b strings.Builder - for i := 0; i < n; i++ { + for i := range n { fmt.Fprintf(&b, "data: {\"id\":%d,\"choices\":[{\"delta\":{\"content\":\"token_%d\"}}]}\n", i, i) } b.WriteString("data: [DONE]\n") @@ -132,7 +132,7 @@ func TestStreamScannerHandler_OrderPreserved(t *testing.T) { }) require.Equal(t, numChunks, len(received)) - for i := 0; i < numChunks; i++ { + for i := range numChunks { expected := fmt.Sprintf("{\"id\":%d,\"choices\":[{\"delta\":{\"content\":\"token_%d\"}}]}", i, i) assert.Equal(t, expected, received[i], "chunk %d out of order", i) } @@ -181,7 +181,7 @@ func TestStreamScannerHandler_SkipsNonDataLines(t *testing.T) { b.WriteString("event: message\n") b.WriteString("id: 12345\n") b.WriteString("retry: 5000\n") - for i := 0; i < 100; i++ { + for i := range 100 { fmt.Fprintf(&b, "data: payload_%d\n", i) b.WriteString(": interleaved comment\n") } @@ -299,7 +299,7 @@ func TestStreamScannerHandler_PingSentDuringSlowUpstream(t *testing.T) { pr, pw := io.Pipe() go func() { defer pw.Close() - for i := 0; i < 4; i++ { + for i := range 4 { fmt.Fprintf(pw, "data: chunk_%d\n", i) time.Sleep(400 * time.Millisecond) } @@ -400,7 +400,7 @@ func TestStreamScannerHandler_StreamStatus_EOFWithoutDone(t *testing.T) { t.Parallel() var b strings.Builder - for i := 0; i < 5; i++ { + for i := range 5 { fmt.Fprintf(&b, "data: {\"id\":%d}\n", i) } c, resp, info := setupStreamTest(t, strings.NewReader(b.String())) @@ -526,7 +526,7 @@ func TestStreamScannerHandler_StreamStatus_ErrorThenStop(t *testing.T) { // Use a large body without [DONE] to avoid race between scanner's [DONE] // and handler's Stop on the sync.Once EndReason. var b strings.Builder - for i := 0; i < 100; i++ { + for i := range 100 { fmt.Fprintf(&b, "data: {\"id\":%d}\n", i) } c, resp, info := setupStreamTest(t, strings.NewReader(b.String())) diff --git a/relay/mjproxy_handler.go b/relay/mjproxy_handler.go index 99755f0f52..b57bc71efc 100644 --- a/relay/mjproxy_handler.go +++ b/relay/mjproxy_handler.go @@ -588,7 +588,7 @@ func RelayMidjourneySubmit(c *gin.Context, relayInfo *relaycommon.RelayInfo) *dt if midjResponse.Code == 21 { //21-任务已存在(处理中或者有结果了) // 将 properties 转换为一个 map - properties, ok := midjResponse.Properties.(map[string]interface{}) + properties, ok := midjResponse.Properties.(map[string]any) if ok { imageUrl, ok1 := properties["imageUrl"].(string) status, ok2 := properties["status"].(string) diff --git a/relay/plugin_protocol.go b/relay/plugin_protocol.go index 617ed3688d..6cb90c51fc 100644 --- a/relay/plugin_protocol.go +++ b/relay/plugin_protocol.go @@ -5,6 +5,7 @@ import ( "encoding/json" "errors" "fmt" + "maps" "math" "sort" "strconv" @@ -835,9 +836,7 @@ func (m *PluginResponsesMachine) finalMetadata(pluginValue any) map[string]strin metadata[key] = value } } - for key, value := range m.metadata { - metadata[key] = value - } + maps.Copy(metadata, m.metadata) return metadata } @@ -1003,9 +1002,7 @@ func (m *PluginResponsesMachine) event(event dto.PluginResponsesStreamEvent) dto func (m *PluginResponsesMachine) responseSnapshot(responseError *dto.PluginResponsesError) *dto.PluginResponsesResponse { metadata := make(map[string]string, len(m.metadata)) - for key, value := range m.metadata { - metadata[key] = value - } + maps.Copy(metadata, m.metadata) outputs := make([]dto.PluginResponsesOutput, len(m.outputs)) for index, output := range m.outputs { outputs[index] = output diff --git a/relay/relay_task.go b/relay/relay_task.go index 42c0e21d81..0c1a79c62c 100644 --- a/relay/relay_task.go +++ b/relay/relay_task.go @@ -77,7 +77,7 @@ func ResolveOriginTask(c *gin.Context, info *relaycommon.RelayInfo) *dto.TaskErr } else if originTask.Properties.UpstreamModelName != "" { info.OriginModelName = originTask.Properties.UpstreamModelName } else { - var taskData map[string]interface{} + var taskData map[string]any _ = common.Unmarshal(originTask.Data, &taskData) if m, ok := taskData["model"].(string); ok && m != "" { info.OriginModelName = m @@ -120,7 +120,7 @@ func ResolveOriginTask(c *gin.Context, info *relaycommon.RelayInfo) *dto.TaskErr } } else { // 旧的 remix 逻辑:直接从 task data 解析 seconds 和 size(如果存在) - var taskData map[string]interface{} + var taskData map[string]any _ = common.Unmarshal(originTask.Data, &taskData) secondsStr, _ := taskData["seconds"].(string) seconds, _ := strconv.Atoi(secondsStr) diff --git a/relay/request_clone_test.go b/relay/request_clone_test.go index 9681137c2e..049dd338b3 100644 --- a/relay/request_clone_test.go +++ b/relay/request_clone_test.go @@ -92,13 +92,13 @@ func populateResponsesCloneFixture(t *testing.T, value reflect.Value, raw json.R for i := 0; i < value.NumField(); i++ { populateResponsesCloneFixture(t, value.Field(i), raw) } - case reflect.Ptr: + case reflect.Pointer: if value.IsNil() { value.Set(reflect.New(value.Type().Elem())) } populateResponsesCloneFixture(t, value.Elem(), raw) case reflect.Slice: - require.Equal(t, reflect.TypeOf(json.RawMessage{}), value.Type()) + require.Equal(t, reflect.TypeFor[json.RawMessage](), value.Type()) if value.Len() > 0 { value.Index(0).SetUint('!') } diff --git a/relaykit/dto/billing_usage.go b/relaykit/dto/billing_usage.go index f8cb491ed7..0949774c00 100644 --- a/relaykit/dto/billing_usage.go +++ b/relaykit/dto/billing_usage.go @@ -122,10 +122,7 @@ func NewEstimatedGeminiChatBillingUsage(usage *Usage) *BillingUsage { return nil } reasoningTokens := usage.CompletionTokenDetails.ReasoningTokens - candidateTokens := usage.CompletionTokens - reasoningTokens - if candidateTokens < 0 { - candidateTokens = 0 - } + candidateTokens := max(usage.CompletionTokens-reasoningTokens, 0) totalTokens := usage.TotalTokens if totalTokens == 0 { totalTokens = usage.PromptTokens + usage.CompletionTokens @@ -191,10 +188,7 @@ func CloneBillingUsageWithEstimatedCompletion(usage *BillingUsage, completionTok case clone.GeminiUsageMetadata != nil: metadata := clone.GeminiUsageMetadata if metadata.CandidatesTokenCount == 0 { - candidateTokens := completionTokens - metadata.ThoughtsTokenCount - if candidateTokens < 0 { - candidateTokens = 0 - } + candidateTokens := max(completionTokens-metadata.ThoughtsTokenCount, 0) metadata.CandidatesTokenCount = candidateTokens totalTokens := metadata.PromptTokenCount + metadata.ToolUsePromptTokenCount + metadata.CandidatesTokenCount + metadata.ThoughtsTokenCount if metadata.TotalTokenCount < totalTokens { @@ -366,10 +360,7 @@ func (usage *BillingUsage) canonicalGeminiUsage() *Usage { if canonical.TotalTokens == 0 { canonical.TotalTokens = canonical.PromptTokens + canonical.CompletionTokens } else if canonical.CompletionTokens <= 0 { - canonical.CompletionTokens = canonical.TotalTokens - canonical.PromptTokens - if canonical.CompletionTokens < 0 { - canonical.CompletionTokens = 0 - } + canonical.CompletionTokens = max(canonical.TotalTokens-canonical.PromptTokens, 0) } if canonical.PromptTokens > 0 && canonical.PromptTokensDetails.TextTokens == 0 && canonical.PromptTokensDetails.AudioTokens == 0 { canonical.PromptTokensDetails.TextTokens = canonical.PromptTokens diff --git a/relaykit/dto/claude.go b/relaykit/dto/claude.go index 46a2f87eae..33a7a863a2 100644 --- a/relaykit/dto/claude.go +++ b/relaykit/dto/claude.go @@ -79,7 +79,7 @@ func (c *ClaudeMediaMessage) GetStringContent() string { case string: return c.Content.(string) case []any: - var contentStr string + var contentStr strings.Builder for _, contentItem := range c.Content.([]any) { contentMap, ok := contentItem.(map[string]any) if !ok { @@ -87,11 +87,11 @@ func (c *ClaudeMediaMessage) GetStringContent() string { } if contentMap["type"] == ContentTypeText { if subStr, ok := contentMap["text"].(string); ok { - contentStr += subStr + contentStr.WriteString(subStr) } } } - return contentStr + return contentStr.String() } return "" @@ -153,7 +153,7 @@ func (c *ClaudeMessage) GetStringContent() string { case string: return c.Content.(string) case []any: - var contentStr string + var contentStr strings.Builder for _, contentItem := range c.Content.([]any) { contentMap, ok := contentItem.(map[string]any) if !ok { @@ -161,11 +161,11 @@ func (c *ClaudeMessage) GetStringContent() string { } if contentMap["type"] == ContentTypeText { if subStr, ok := contentMap["text"].(string); ok { - contentStr += subStr + contentStr.WriteString(subStr) } } } - return contentStr + return contentStr.String() } return "" @@ -184,10 +184,10 @@ func (c *ClaudeMessage) ParseContent() ([]ClaudeMediaMessage, error) { } type Tool struct { - Name string `json:"name"` - Description string `json:"description,omitempty"` - InputSchema map[string]interface{} `json:"input_schema"` - Strict *bool `json:"strict,omitempty"` + Name string `json:"name"` + Description string `json:"description,omitempty"` + InputSchema map[string]any `json:"input_schema"` + Strict *bool `json:"strict,omitempty"` } type InputSchema struct { @@ -547,7 +547,7 @@ func (c *ClaudeResponse) GetClaudeError() *types.ClaudeError { return &err case *types.ClaudeError: return err - case map[string]interface{}: + case map[string]any: // 处理从JSON解析来的map结构 claudeErr := &types.ClaudeError{} if errType, ok := err["type"].(string); ok { diff --git a/relaykit/dto/gemini.go b/relaykit/dto/gemini.go index 3a68a0203a..4997645a1f 100644 --- a/relaykit/dto/gemini.go +++ b/relaykit/dto/gemini.go @@ -13,7 +13,7 @@ type GeminiChatRequest struct { Requests []GeminiChatRequest `json:"requests,omitempty"` // For batch requests Contents []GeminiChatContent `json:"contents"` SafetySettings []GeminiChatSafetySettings `json:"safetySettings,omitempty"` - GenerationConfig GeminiChatGenerationConfig `json:"generationConfig,omitempty"` + GenerationConfig GeminiChatGenerationConfig `json:"generationConfig"` Tools json.RawMessage `json:"tools,omitempty"` ToolConfig *ToolConfig `json:"toolConfig,omitempty"` SystemInstructions *GeminiChatContent `json:"systemInstruction,omitempty"` @@ -258,12 +258,12 @@ type GeminiPartialArg struct { } type GeminiFunctionResponse struct { - Name string `json:"name"` - Response map[string]interface{} `json:"response"` - WillContinue json.RawMessage `json:"willContinue,omitempty"` - Scheduling json.RawMessage `json:"scheduling,omitempty"` - Parts json.RawMessage `json:"parts,omitempty"` - ID json.RawMessage `json:"id,omitempty"` + Name string `json:"name"` + Response map[string]any `json:"response"` + WillContinue json.RawMessage `json:"willContinue,omitempty"` + Scheduling json.RawMessage `json:"scheduling,omitempty"` + Parts json.RawMessage `json:"parts,omitempty"` + ID json.RawMessage `json:"id,omitempty"` } type GeminiPartExecutableCode struct { diff --git a/relaykit/dto/notify.go b/relaykit/dto/notify.go index b75cec70ca..8e17ab76f3 100644 --- a/relaykit/dto/notify.go +++ b/relaykit/dto/notify.go @@ -1,10 +1,10 @@ package dto type Notify struct { - Type string `json:"type"` - Title string `json:"title"` - Content string `json:"content"` - Values []interface{} `json:"values"` + Type string `json:"type"` + Title string `json:"title"` + Content string `json:"content"` + Values []any `json:"values"` } const ContentValueParam = "{{value}}" @@ -15,7 +15,7 @@ const ( NotifyTypeChannelTest = "channel_test" ) -func NewNotify(t string, title string, content string, values []interface{}) Notify { +func NewNotify(t string, title string, content string, values []any) Notify { return Notify{ Type: t, Title: title, diff --git a/relaykit/dto/openai_image.go b/relaykit/dto/openai_image.go index ef9c6fb042..5281cb391e 100644 --- a/relaykit/dto/openai_image.go +++ b/relaykit/dto/openai_image.go @@ -50,7 +50,7 @@ func (i *ImageRequest) UnmarshalJSON(data []byte) error { } // 用 struct tag 获取所有已定义字段名 - knownFields := GetJSONFieldNames(reflect.TypeOf(*i)) + knownFields := GetJSONFieldNames(reflect.TypeFor[ImageRequest]()) // 再正常解析已定义字段 type Alias ImageRequest diff --git a/relaykit/dto/openai_request.go b/relaykit/dto/openai_request.go index aebbbe9784..d05c6bf1c1 100644 --- a/relaykit/dto/openai_request.go +++ b/relaykit/dto/openai_request.go @@ -369,7 +369,7 @@ const CustomType = "custom" type ToolCallRequest struct { ID string `json:"id,omitempty"` Type string `json:"type"` - Function FunctionRequest `json:"function,omitempty"` + Function FunctionRequest `json:"function"` Custom json.RawMessage `json:"custom,omitempty"` } @@ -620,7 +620,7 @@ func (m *Message) StringContent() string { case string: return m.Content.(string) case []any: - var contentStr string + var contentStr strings.Builder for _, contentItem := range m.Content.([]any) { contentMap, ok := contentItem.(map[string]any) if !ok { @@ -628,11 +628,11 @@ func (m *Message) StringContent() string { } if contentMap["type"] == ContentTypeText { if subStr, ok := contentMap["text"].(string); ok { - contentStr += subStr + contentStr.WriteString(subStr) } } } - return contentStr + return contentStr.String() } return "" @@ -727,7 +727,7 @@ func (m *Message) ParseContent() []MediaContent { switch v := imageUrl.(type) { case string: temp.Url = v - case map[string]interface{}: + case map[string]any: url, ok1 := v["url"].(string) detail, ok2 := v["detail"].(string) if ok2 { @@ -743,7 +743,7 @@ func (m *Message) ParseContent() []MediaContent { }) case ContentTypeInputAudio: - if audioData, ok := contentItem["input_audio"].(map[string]interface{}); ok { + if audioData, ok := contentItem["input_audio"].(map[string]any); ok { data, ok1 := audioData["data"].(string) format, ok2 := audioData["format"].(string) if ok1 && ok2 { @@ -758,7 +758,7 @@ func (m *Message) ParseContent() []MediaContent { } } case ContentTypeFile: - if fileData, ok := contentItem["file"].(map[string]interface{}); ok { + if fileData, ok := contentItem["file"].(map[string]any); ok { fileId, ok3 := fileData["file_id"].(string) if ok3 { contentList = append(contentList, MediaContent{ diff --git a/relaykit/dto/openai_response.go b/relaykit/dto/openai_response.go index 6ab5c6fcf0..9bea78623f 100644 --- a/relaykit/dto/openai_response.go +++ b/relaykit/dto/openai_response.go @@ -80,7 +80,7 @@ type FlexibleEmbeddingResponse struct { } type ChatCompletionsStreamResponseChoice struct { - Delta ChatCompletionsStreamResponseChoiceDelta `json:"delta,omitempty"` + Delta ChatCompletionsStreamResponseChoiceDelta `json:"delta"` Logprobs *any `json:"logprobs"` FinishReason *string `json:"finish_reason"` Index int `json:"index"` @@ -278,10 +278,7 @@ type InputTokenDetails struct { // value wins so the same tokens are never double-counted. Negative upstream // values are clamped to zero so they can never lower a charge. func (d InputTokenDetails) CacheCreationTokensTotal() int { - total := d.CachedCreationTokens - if d.CacheWriteTokens > total { - total = d.CacheWriteTokens - } + total := max(d.CacheWriteTokens, d.CachedCreationTokens) if total < 0 { return 0 } @@ -483,9 +480,9 @@ func ResponsesArgumentsString(arguments json.RawMessage) string { } type ResponsesOutputContent struct { - Type string `json:"type"` - Text string `json:"text"` - Annotations []interface{} `json:"annotations"` + Type string `json:"type"` + Text string `json:"text"` + Annotations []any `json:"annotations"` } type ResponsesReasoningSummaryPart struct { @@ -549,7 +546,7 @@ func GetOpenAIError(errorField any) *types.OpenAIError { return &err case *types.OpenAIError: return err - case map[string]interface{}: + case map[string]any: // 处理从JSON解析来的map结构 openaiErr := &types.OpenAIError{} if errType, ok := err["type"].(string); ok { diff --git a/relaykit/dto/pricing.go b/relaykit/dto/pricing.go index a32bd2a6ac..929e563378 100644 --- a/relaykit/dto/pricing.go +++ b/relaykit/dto/pricing.go @@ -19,17 +19,17 @@ type AnthropicModel struct { } type GeminiModel struct { - Name interface{} `json:"name"` - BaseModelId interface{} `json:"baseModelId"` - Version interface{} `json:"version"` - DisplayName interface{} `json:"displayName"` - Description interface{} `json:"description"` - InputTokenLimit interface{} `json:"inputTokenLimit"` - OutputTokenLimit interface{} `json:"outputTokenLimit"` - SupportedGenerationMethods []interface{} `json:"supportedGenerationMethods"` - Thinking interface{} `json:"thinking"` - Temperature interface{} `json:"temperature"` - MaxTemperature interface{} `json:"maxTemperature"` - TopP interface{} `json:"topP"` - TopK interface{} `json:"topK"` + Name any `json:"name"` + BaseModelId any `json:"baseModelId"` + Version any `json:"version"` + DisplayName any `json:"displayName"` + Description any `json:"description"` + InputTokenLimit any `json:"inputTokenLimit"` + OutputTokenLimit any `json:"outputTokenLimit"` + SupportedGenerationMethods []any `json:"supportedGenerationMethods"` + Thinking any `json:"thinking"` + Temperature any `json:"temperature"` + MaxTemperature any `json:"maxTemperature"` + TopP any `json:"topP"` + TopK any `json:"topK"` } diff --git a/relaykit/dto/ratio_sync.go b/relaykit/dto/ratio_sync.go index 83906c83a1..e47cd82869 100644 --- a/relaykit/dto/ratio_sync.go +++ b/relaykit/dto/ratio_sync.go @@ -25,9 +25,9 @@ type TestResult struct { // Upstreams 为各渠道的上游值,具体数值 / "same" / nil type DifferenceItem struct { - Current interface{} `json:"current"` - Upstreams map[string]interface{} `json:"upstreams"` - Confidence map[string]bool `json:"confidence"` + Current any `json:"current"` + Upstreams map[string]any `json:"upstreams"` + Confidence map[string]bool `json:"confidence"` } type SyncableChannel struct { diff --git a/relaykit/dto/realtime.go b/relaykit/dto/realtime.go index ac5dc6445a..b38c25302a 100644 --- a/relaykit/dto/realtime.go +++ b/relaykit/dto/realtime.go @@ -52,7 +52,7 @@ type RealtimeSession struct { InputAudioFormat string `json:"input_audio_format"` OutputAudioFormat string `json:"output_audio_format"` InputAudioTranscription InputAudioTranscription `json:"input_audio_transcription"` - TurnDetection interface{} `json:"turn_detection"` + TurnDetection any `json:"turn_detection"` Tools []RealTimeTool `json:"tools"` ToolChoice string `json:"tool_choice"` Temperature float64 `json:"temperature"` diff --git a/relaykit/relayconvert/internal/claude_messages/citations.go b/relaykit/relayconvert/internal/claude_messages/citations.go index cd97eb3029..9d67fdc905 100644 --- a/relaykit/relayconvert/internal/claude_messages/citations.go +++ b/relaykit/relayconvert/internal/claude_messages/citations.go @@ -30,8 +30,8 @@ func claudeCitationsToChat(raw json.RawMessage, text string, textOffset int) ([] citedText := kitutil.Interface2String(citation["cited_text"]) if citedText != "" { converted["cited_text"] = citedText - if index := strings.Index(text, citedText); index >= 0 { - startIndex := textOffset + utf8.RuneCountInString(text[:index]) + if before, _, ok := strings.Cut(text, citedText); ok { + startIndex := textOffset + utf8.RuneCountInString(before) converted["start_index"] = startIndex converted["end_index"] = startIndex + utf8.RuneCountInString(citedText) } diff --git a/relaykit/relayconvert/internal/claude_messages/to_oai_chat_req.go b/relaykit/relayconvert/internal/claude_messages/to_oai_chat_req.go index fa1a3c1d80..cacdff74a0 100644 --- a/relaykit/relayconvert/internal/claude_messages/to_oai_chat_req.go +++ b/relaykit/relayconvert/internal/claude_messages/to_oai_chat_req.go @@ -140,13 +140,13 @@ func ClaudeMessagesRequestToOpenAIChat(claudeRequest dto.ClaudeRequest, info con } openAIMessage.SetMediaContent(systemMediaMessages) } else { - systemStr := "" + var systemStr strings.Builder for _, system := range systems { if system.Text != nil { - systemStr += *system.Text + systemStr.WriteString(*system.Text) } } - openAIMessage.SetStringContent(systemStr) + openAIMessage.SetStringContent(systemStr.String()) } openAIMessages = append(openAIMessages, openAIMessage) } @@ -230,7 +230,7 @@ func ClaudeMessagesRequestToOpenAIChat(claudeRequest dto.ClaudeRequest, info con return &openAIRequest, nil } -func requestToJSONString(v interface{}) string { +func requestToJSONString(v any) string { b, err := kitutil.Marshal(v) if err != nil { return "{}" diff --git a/relaykit/relayconvert/internal/oai_chat/to_claude_messages_req.go b/relaykit/relayconvert/internal/oai_chat/to_claude_messages_req.go index 4f0330b29a..cbbe40a2b7 100644 --- a/relaykit/relayconvert/internal/oai_chat/to_claude_messages_req.go +++ b/relaykit/relayconvert/internal/oai_chat/to_claude_messages_req.go @@ -5,6 +5,7 @@ import ( "strings" "context" + "github.com/QuantumNous/new-api/relaykit/dto" "github.com/QuantumNous/new-api/relaykit/relayconvert/convmeta" relaymedia "github.com/QuantumNous/new-api/relaykit/relayconvert/internal/media" @@ -39,9 +40,9 @@ func OpenAIChatRequestToClaudeMessages(c context.Context, info convmeta.Meta, te Type: "approximate", } - var userLocationMap map[string]interface{} + var userLocationMap map[string]any if err := kitutil.Unmarshal(textRequest.WebSearchOptions.UserLocation, &userLocationMap); err == nil { - if approximateData, ok := userLocationMap["approximate"].(map[string]interface{}); ok { + if approximateData, ok := userLocationMap["approximate"].(map[string]any); ok { if timezone, ok := approximateData["timezone"].(string); ok && timezone != "" { anthropicUserLocation.Timezone = timezone } @@ -111,7 +112,7 @@ func OpenAIChatRequestToClaudeMessages(c context.Context, info convmeta.Meta, te switch stop := textRequest.Stop.(type) { case string: claudeRequest.StopSequences = []string{stop} - case []interface{}: + case []any: stopSequences := make([]string, 0) for _, item := range stop { stopSequences = append(stopSequences, item.(string)) diff --git a/relaykit/relayconvert/internal/oai_chat/to_claude_messages_resp.go b/relaykit/relayconvert/internal/oai_chat/to_claude_messages_resp.go index 06e11356fd..fe11c311e3 100644 --- a/relaykit/relayconvert/internal/oai_chat/to_claude_messages_resp.go +++ b/relaykit/relayconvert/internal/oai_chat/to_claude_messages_resp.go @@ -65,7 +65,7 @@ func startPendingToolBlocks(state *convmeta.ClaudeConvertInfo) []*dto.ClaudeResp Id: tool.ID, Type: "tool_use", Name: tool.Name, - Input: map[string]interface{}{}, + Input: map[string]any{}, }, }) tool.Started = true @@ -304,7 +304,7 @@ func StreamResponseOpenAI2Claude(openAIResponse *dto.ChatCompletionsStreamRespon Id: tool.ID, Type: "tool_use", Name: tool.Name, - Input: map[string]interface{}{}, + Input: map[string]any{}, }, }) tool.Started = true @@ -480,9 +480,9 @@ func ResponseOpenAI2Claude(openAIResponse *dto.OpenAITextResponse, info convmeta claudeContent.Type = "tool_use" claudeContent.Id = toolUse.ID claudeContent.Name = toolUse.Function.Name - mapParams := map[string]interface{}{} + mapParams := map[string]any{} if strings.TrimSpace(toolUse.Function.Arguments) != "" { - var parsed map[string]interface{} + var parsed map[string]any if err := kitutil.Unmarshal([]byte(toolUse.Function.Arguments), &parsed); err == nil && parsed != nil { mapParams = parsed } diff --git a/relaykit/relayconvert/internal/oai_chat/to_claude_messages_resp_test.go b/relaykit/relayconvert/internal/oai_chat/to_claude_messages_resp_test.go index cbb38813da..e7d1de7f0f 100644 --- a/relaykit/relayconvert/internal/oai_chat/to_claude_messages_resp_test.go +++ b/relaykit/relayconvert/internal/oai_chat/to_claude_messages_resp_test.go @@ -13,14 +13,14 @@ func TestResponseOpenAI2ClaudeToolUseInputIsObject(t *testing.T) { tests := []struct { name string args string - want map[string]interface{} + want map[string]any }{ - {name: "object", args: `{"q":"x"}`, want: map[string]interface{}{"q": "x"}}, - {name: "empty", args: "", want: map[string]interface{}{}}, - {name: "invalid", args: "{", want: map[string]interface{}{}}, - {name: "null", args: "null", want: map[string]interface{}{}}, - {name: "array", args: `["x"]`, want: map[string]interface{}{}}, - {name: "string", args: `"x"`, want: map[string]interface{}{}}, + {name: "object", args: `{"q":"x"}`, want: map[string]any{"q": "x"}}, + {name: "empty", args: "", want: map[string]any{}}, + {name: "invalid", args: "{", want: map[string]any{}}, + {name: "null", args: "null", want: map[string]any{}}, + {name: "array", args: `["x"]`, want: map[string]any{}}, + {name: "string", args: `"x"`, want: map[string]any{}}, } for _, tt := range tests { diff --git a/relaykit/relayconvert/internal/oai_chat/to_gemini_chat_req.go b/relaykit/relayconvert/internal/oai_chat/to_gemini_chat_req.go index 7e721632bc..bdd75b4b53 100644 --- a/relaykit/relayconvert/internal/oai_chat/to_gemini_chat_req.go +++ b/relaykit/relayconvert/internal/oai_chat/to_gemini_chat_req.go @@ -7,6 +7,7 @@ import ( "strings" "context" + "github.com/QuantumNous/new-api/relaykit/dto" "github.com/QuantumNous/new-api/relaykit/relayconvert/convmeta" relaymedia "github.com/QuantumNous/new-api/relaykit/relayconvert/internal/media" @@ -55,17 +56,17 @@ func OpenAIChatRequestToGeminiGenerateContent(c context.Context, textRequest dto } if len(textRequest.ExtraBody) > 0 { - var extraBody map[string]interface{} + var extraBody map[string]any if err := kitutil.Unmarshal(textRequest.ExtraBody, &extraBody); err != nil { return nil, fmt.Errorf("invalid extra body: %w", err) } - if googleBody, ok := extraBody["google"].(map[string]interface{}); ok { + if googleBody, ok := extraBody["google"].(map[string]any); ok { if _, hasErrorParam := googleBody["thinkingConfig"]; hasErrorParam { return nil, errors.New("extra_body.google.thinkingConfig is not supported, use extra_body.google.thinking_config instead") } - if thinkingConfig, ok := googleBody["thinking_config"].(map[string]interface{}); ok { + if thinkingConfig, ok := googleBody["thinking_config"].(map[string]any); ok { if _, hasErrorParam := thinkingConfig["thinkingBudget"]; hasErrorParam { return nil, errors.New("extra_body.google.thinking_config.thinkingBudget is not supported, use extra_body.google.thinking_config.thinking_budget instead") } @@ -109,7 +110,7 @@ func OpenAIChatRequestToGeminiGenerateContent(c context.Context, textRequest dto return nil, errors.New("extra_body.google.imageConfig is not supported, use extra_body.google.image_config instead") } - if imageConfig, ok := googleBody["image_config"].(map[string]interface{}); ok { + if imageConfig, ok := googleBody["image_config"].(map[string]any); ok { if _, hasErrorParam := imageConfig["aspectRatio"]; hasErrorParam { return nil, errors.New("extra_body.google.image_config.aspectRatio is not supported, use extra_body.google.image_config.aspect_ratio instead") } @@ -117,7 +118,7 @@ func OpenAIChatRequestToGeminiGenerateContent(c context.Context, textRequest dto return nil, errors.New("extra_body.google.image_config.imageSize is not supported, use extra_body.google.image_config.image_size instead") } - geminiImageConfig := make(map[string]interface{}) + geminiImageConfig := make(map[string]any) if aspectRatio, ok := imageConfig["aspect_ratio"]; ok { geminiImageConfig["aspectRatio"] = aspectRatio } @@ -159,8 +160,8 @@ func OpenAIChatRequestToGeminiGenerateContent(c context.Context, textRequest dto functions := make([]dto.FunctionRequest, 0, len(textRequest.Tools)) for _, tool := range textRequest.Tools { if tool.Function.Parameters != nil { - if params, ok := tool.Function.Parameters.(map[string]interface{}); ok { - if props, hasProps := params["properties"].(map[string]interface{}); hasProps && len(props) == 0 { + if params, ok := tool.Function.Parameters.(map[string]any); ok { + if props, hasProps := params["properties"].(map[string]any); hasProps && len(props) == 0 { tool.Function.Parameters = nil } } @@ -213,15 +214,15 @@ func OpenAIChatRequestToGeminiGenerateContent(c context.Context, textRequest dto } else if val, exists := toolCallIDs[message.ToolCallId]; exists { name = val } - var contentMap map[string]interface{} + var contentMap map[string]any contentStr := message.StringContent() if err := kitutil.Unmarshal([]byte(contentStr), &contentMap); err != nil { - var contentSlice []interface{} + var contentSlice []any if err := kitutil.Unmarshal([]byte(contentStr), &contentSlice); err == nil { - contentMap = map[string]interface{}{"result": contentSlice} + contentMap = map[string]any{"result": contentSlice} } else { - contentMap = map[string]interface{}{"content": contentStr} + contentMap = map[string]any{"content": contentStr} } } @@ -251,7 +252,7 @@ func OpenAIChatRequestToGeminiGenerateContent(c context.Context, textRequest dto signatureAttached := false if message.ToolCalls != nil { for _, call := range message.ParseToolCalls() { - args := map[string]interface{}{} + args := map[string]any{} if call.Function.Arguments != "" { if kitutil.Unmarshal([]byte(call.Function.Arguments), &args) != nil { return nil, fmt.Errorf("invalid arguments for function %s, args: %s", call.Function.Name, call.Function.Arguments) diff --git a/relaykit/relayconvert/internal/oai_chat/to_gemini_chat_resp.go b/relaykit/relayconvert/internal/oai_chat/to_gemini_chat_resp.go index 4671b2dc50..387668b522 100644 --- a/relaykit/relayconvert/internal/oai_chat/to_gemini_chat_resp.go +++ b/relaykit/relayconvert/internal/oai_chat/to_gemini_chat_resp.go @@ -502,17 +502,17 @@ func newGeminiStreamResponse(candidates []dto.GeminiChatCandidate, usage *dto.Us return response } -func geminiFunctionArguments(raw string) map[string]interface{} { +func geminiFunctionArguments(raw string) map[string]any { if strings.TrimSpace(raw) == "" || strings.TrimSpace(raw) == "null" { - return map[string]interface{}{} + return map[string]any{} } - var args map[string]interface{} + var args map[string]any if err := kitutil.Unmarshal([]byte(raw), &args); err == nil && args != nil { return args } // Preserve historically accepted malformed/non-object input without // emitting a non-object Gemini args value. - return map[string]interface{}{"arguments": raw} + return map[string]any{"arguments": raw} } func geminiFinishReason(finishReason string) string { diff --git a/relaykit/relayconvert/internal/oai_chat/to_gemini_chat_resp_test.go b/relaykit/relayconvert/internal/oai_chat/to_gemini_chat_resp_test.go index 4e20baf4a8..9e7feefd5d 100644 --- a/relaykit/relayconvert/internal/oai_chat/to_gemini_chat_resp_test.go +++ b/relaykit/relayconvert/internal/oai_chat/to_gemini_chat_resp_test.go @@ -60,7 +60,7 @@ func TestResponseOpenAI2GeminiMapsTextToolFinishReasonAndUsage(t *testing.T) { assert.Equal(t, "hello", resp.Candidates[0].Content.Parts[0].Text) require.NotNil(t, resp.Candidates[0].Content.Parts[1].FunctionCall) assert.Equal(t, "lookup", resp.Candidates[0].Content.Parts[1].FunctionCall.FunctionName) - assert.Equal(t, map[string]interface{}{"q": "x"}, resp.Candidates[0].Content.Parts[1].FunctionCall.Arguments) + assert.Equal(t, map[string]any{"q": "x"}, resp.Candidates[0].Content.Parts[1].FunctionCall.Arguments) } func TestStreamResponseOpenAI2GeminiMapsToolCallFinishReasonAndUsage(t *testing.T) { @@ -104,7 +104,7 @@ func TestStreamResponseOpenAI2GeminiMapsToolCallFinishReasonAndUsage(t *testing. require.Len(t, resp.Candidates[0].Content.Parts, 1) require.NotNil(t, resp.Candidates[0].Content.Parts[0].FunctionCall) assert.Equal(t, "lookup", resp.Candidates[0].Content.Parts[0].FunctionCall.FunctionName) - assert.Equal(t, map[string]interface{}{"q": "x"}, resp.Candidates[0].Content.Parts[0].FunctionCall.Arguments) + assert.Equal(t, map[string]any{"q": "x"}, resp.Candidates[0].Content.Parts[0].FunctionCall.Arguments) } func geminiRespPtr[T any](value T) *T { diff --git a/relaykit/relayconvert/internal/oai_chat/to_oai_responses_resp.go b/relaykit/relayconvert/internal/oai_chat/to_oai_responses_resp.go index 5fc35dd3ae..4d1707b9d8 100644 --- a/relaykit/relayconvert/internal/oai_chat/to_oai_responses_resp.go +++ b/relaykit/relayconvert/internal/oai_chat/to_oai_responses_resp.go @@ -3,6 +3,7 @@ package oaichat import ( "errors" "fmt" + "maps" "strings" "time" @@ -102,15 +103,15 @@ func ChatCompletionsResponseToResponsesResponse(resp *dto.OpenAITextResponse, id return out, usage, nil } -func chatAnnotationsToResponses(raw []byte) ([]interface{}, error) { +func chatAnnotationsToResponses(raw []byte) ([]any, error) { if len(raw) == 0 { - return []interface{}{}, nil + return []any{}, nil } var annotations []map[string]any if err := kitutil.Unmarshal(raw, &annotations); err != nil { return nil, fmt.Errorf("invalid Chat annotations: %w", err) } - converted := make([]interface{}, 0, len(annotations)) + converted := make([]any, 0, len(annotations)) for _, annotation := range annotations { if strings.TrimSpace(kitutil.Interface2String(annotation["type"])) != "url_citation" { converted = append(converted, annotation) @@ -123,9 +124,7 @@ func chatAnnotationsToResponses(raw []byte) ([]interface{}, error) { } flattened := make(map[string]any, len(citation)+1) flattened["type"] = "url_citation" - for key, value := range citation { - flattened[key] = value - } + maps.Copy(flattened, citation) converted = append(converted, flattened) } return converted, nil diff --git a/relaykit/relayconvert/internal/oai_chat/to_oai_responses_stream_resp.go b/relaykit/relayconvert/internal/oai_chat/to_oai_responses_stream_resp.go index 1cb4345942..b13422804a 100644 --- a/relaykit/relayconvert/internal/oai_chat/to_oai_responses_stream_resp.go +++ b/relaykit/relayconvert/internal/oai_chat/to_oai_responses_stream_resp.go @@ -42,7 +42,7 @@ type ChatToResponsesStreamState struct { hostedByID map[string]*chatToResponsesHostedTool outputOrder []chatToResponsesOutputRef text strings.Builder - annotations []interface{} + annotations []any reasoning strings.Builder } @@ -730,7 +730,7 @@ func (s *ChatToResponsesStreamState) reasoningID() string { func (s *ChatToResponsesStreamState) messageOutput(status string) *dto.ResponsesOutput { annotations := s.annotations if annotations == nil { - annotations = []interface{}{} + annotations = []any{} } return &dto.ResponsesOutput{ Type: responsesOutputTypeMessage, diff --git a/relaykit/relayconvert/internal/oai_responses/req_helpers.go b/relaykit/relayconvert/internal/oai_responses/req_helpers.go index 15544b2c29..c80f3e281f 100644 --- a/relaykit/relayconvert/internal/oai_responses/req_helpers.go +++ b/relaykit/relayconvert/internal/oai_responses/req_helpers.go @@ -166,30 +166,30 @@ func ObjectValue(value any, fallbackKey string) map[string]any { return responsesObjectValue(value, fallbackKey) } -func responsesGeminiResponseMap(value any) map[string]interface{} { +func responsesGeminiResponseMap(value any) map[string]any { switch typed := value.(type) { case nil: - return map[string]interface{}{} + return map[string]any{} case map[string]any: return typed case string: - var object map[string]interface{} + var object map[string]any if err := kitutil.Unmarshal([]byte(typed), &object); err == nil { return object } - var array []interface{} + var array []any if err := kitutil.Unmarshal([]byte(typed), &array); err == nil { - return map[string]interface{}{"result": array} + return map[string]any{"result": array} } - return map[string]interface{}{"content": typed} + return map[string]any{"content": typed} case []any: - return map[string]interface{}{"result": typed} + return map[string]any{"result": typed} default: - return map[string]interface{}{"content": typed} + return map[string]any{"content": typed} } } -func GeminiResponseMap(value any) map[string]interface{} { +func GeminiResponseMap(value any) map[string]any { return responsesGeminiResponseMap(value) } diff --git a/relaykit/relayconvert/internal/oai_responses/to_claude_messages_resp.go b/relaykit/relayconvert/internal/oai_responses/to_claude_messages_resp.go index 51482ab188..aba78bb143 100644 --- a/relaykit/relayconvert/internal/oai_responses/to_claude_messages_resp.go +++ b/relaykit/relayconvert/internal/oai_responses/to_claude_messages_resp.go @@ -92,7 +92,7 @@ func responsesClaudeStopReason(resp *dto.OpenAIResponsesResponse, sawToolCall bo return "end_turn" } -func responsesAnnotationsToClaude(annotations []interface{}, text string) []json.RawMessage { +func responsesAnnotationsToClaude(annotations []any, text string) []json.RawMessage { citations := make([]json.RawMessage, 0, len(annotations)) for _, rawAnnotation := range annotations { annotation, err := kitutil.Any2Type[map[string]any](rawAnnotation) diff --git a/relaykit/relayconvert/internal/oai_responses/to_claude_messages_stream_resp_test.go b/relaykit/relayconvert/internal/oai_responses/to_claude_messages_stream_resp_test.go index b20c986069..e9ecd207f7 100644 --- a/relaykit/relayconvert/internal/oai_responses/to_claude_messages_stream_resp_test.go +++ b/relaykit/relayconvert/internal/oai_responses/to_claude_messages_stream_resp_test.go @@ -1,6 +1,7 @@ package oairesponses import ( + "strings" "testing" "github.com/QuantumNous/new-api/relaykit/dto" @@ -105,7 +106,7 @@ func responsesOfType(responses []*dto.ClaudeResponse, responseType string) []*dt } func joinedClaudeDeltas(responses []*dto.ClaudeResponse, deltaType string) string { - result := "" + var result strings.Builder for _, response := range responses { if response == nil || response.Type != "content_block_delta" || response.Delta == nil || response.Delta.Type != deltaType { continue @@ -113,17 +114,17 @@ func joinedClaudeDeltas(responses []*dto.ClaudeResponse, deltaType string) strin switch deltaType { case "thinking_delta": if response.Delta.Thinking != nil { - result += *response.Delta.Thinking + result.WriteString(*response.Delta.Thinking) } case "text_delta": if response.Delta.Text != nil { - result += *response.Delta.Text + result.WriteString(*response.Delta.Text) } case "input_json_delta": if response.Delta.PartialJson != nil { - result += *response.Delta.PartialJson + result.WriteString(*response.Delta.PartialJson) } } } - return result + return result.String() } diff --git a/relaykit/relayconvert/internal/oai_responses/to_gemini_chat_req.go b/relaykit/relayconvert/internal/oai_responses/to_gemini_chat_req.go index 41fc03fc01..972e8af8ed 100644 --- a/relaykit/relayconvert/internal/oai_responses/to_gemini_chat_req.go +++ b/relaykit/relayconvert/internal/oai_responses/to_gemini_chat_req.go @@ -5,6 +5,7 @@ import ( "strings" "context" + "github.com/QuantumNous/new-api/relaykit/dto" "github.com/QuantumNous/new-api/relaykit/relayconvert/convmeta" relaymedia "github.com/QuantumNous/new-api/relaykit/relayconvert/internal/media" @@ -94,8 +95,8 @@ func OpenAIResponsesRequestToGeminiChat(c context.Context, req *dto.OpenAIRespon return nil, err } for i := range functions { - if params, ok := functions[i].Parameters.(map[string]interface{}); ok { - if props, hasProps := params["properties"].(map[string]interface{}); hasProps && len(props) == 0 { + if params, ok := functions[i].Parameters.(map[string]any); ok { + if props, hasProps := params["properties"].(map[string]any); hasProps && len(props) == 0 { functions[i].Parameters = nil continue } diff --git a/relaykit/relayconvert/internal/oai_responses/to_oai_chat_resp_test.go b/relaykit/relayconvert/internal/oai_responses/to_oai_chat_resp_test.go index 100289bb64..d676525bc1 100644 --- a/relaykit/relayconvert/internal/oai_responses/to_oai_chat_resp_test.go +++ b/relaykit/relayconvert/internal/oai_responses/to_oai_chat_resp_test.go @@ -1,6 +1,7 @@ package oairesponses import ( + "strings" "testing" "github.com/QuantumNous/new-api/relaykit/dto" @@ -332,7 +333,7 @@ func TestResponsesStreamEventToChatChunksDoesNotResendToolOnTerminalOutput(t *te }, })...) - totalArgs := "" + var totalArgs strings.Builder toolIndexes := map[int]bool{} var finishReason string for _, chunk := range chunks { @@ -340,7 +341,7 @@ func TestResponsesStreamEventToChatChunksDoesNotResendToolOnTerminalOutput(t *te for _, tc := range choice.Delta.ToolCalls { require.NotNil(t, tc.Index) toolIndexes[*tc.Index] = true - totalArgs += tc.Function.Arguments + totalArgs.WriteString(tc.Function.Arguments) } if choice.FinishReason != nil { finishReason = *choice.FinishReason @@ -349,7 +350,7 @@ func TestResponsesStreamEventToChatChunksDoesNotResendToolOnTerminalOutput(t *te } assert.Equal(t, map[int]bool{0: true}, toolIndexes) - assert.Equal(t, `{"q":"x"}`, totalArgs) + assert.Equal(t, `{"q":"x"}`, totalArgs.String()) assert.Equal(t, "tool_calls", finishReason) } diff --git a/relaykit/relayconvert/internal/oai_responses/to_oai_chat_stream_resp.go b/relaykit/relayconvert/internal/oai_responses/to_oai_chat_stream_resp.go index 645b169fbb..2b30b5c27c 100644 --- a/relaykit/relayconvert/internal/oai_responses/to_oai_chat_stream_resp.go +++ b/relaykit/relayconvert/internal/oai_responses/to_oai_chat_stream_resp.go @@ -257,10 +257,7 @@ func (s *ResponsesToChatStreamState) remainingAnnotationChunks(output *dto.Respo for _, content := range output.Content { annotations = append(annotations, content.Annotations...) } - start := s.sentAnnotationCount - offset - if start < 0 { - start = 0 - } + start := max(s.sentAnnotationCount-offset, 0) if start >= len(annotations) { return nil, nil } @@ -579,8 +576,8 @@ func (s *ResponsesToChatStreamState) flushAllPendingTools() []dto.ChatCompletion tool := s.toolByKey[key] if tool == nil { callID := strings.TrimPrefix(key, "item:") - if strings.HasPrefix(key, "output:") { - callID = "call_output_" + strings.TrimPrefix(key, "output:") + if after, ok := strings.CutPrefix(key, "output:"); ok { + callID = "call_output_" + after } tool = &responsesStreamTool{ Key: key, @@ -597,8 +594,8 @@ func (s *ResponsesToChatStreamState) flushAllPendingTools() []dto.ChatCompletion delete(s.pendingArgsByOutputIndex, outputIndex) } } - if strings.HasPrefix(key, "item:") { - itemID := strings.TrimPrefix(key, "item:") + if after, ok := strings.CutPrefix(key, "item:"); ok { + itemID := after tool.Arguments += s.pendingArgsByItemID[itemID] delete(s.pendingArgsByItemID, itemID) } @@ -660,7 +657,7 @@ type responsesBufferedItem struct { Type string ID string Text strings.Builder - Annotations []interface{} + Annotations []any ToolIndex int NeedsReasoningBreak bool } @@ -694,7 +691,7 @@ func (a *ResponsesBufferedAccumulator) ProcessEvent(event *dto.ResponsesStreamRe item.Text.WriteString(event.Delta) case responsesEventOutputTextAnnotationAdded: item := a.ensureItem(event, responsesOutputTypeMessage) - var annotation interface{} + var annotation any if err := kitutil.Unmarshal(event.Annotation, &annotation); err == nil && annotation != nil { item.Annotations = append(item.Annotations, annotation) } diff --git a/relaykit/relayconvert/internal/toolconv/decode.go b/relaykit/relayconvert/internal/toolconv/decode.go index ba64370bbc..2a66d1d2ee 100644 --- a/relaykit/relayconvert/internal/toolconv/decode.go +++ b/relaykit/relayconvert/internal/toolconv/decode.go @@ -46,7 +46,6 @@ func extractOpenAIChatRequest(request any) (any, Set, error) { return nil, Set{}, fmt.Errorf("invalid legacy functions: %w", err) } for _, function := range functions { - function := function set.Definitions = append(set.Definitions, Definition{ Kind: KindFunction, Execution: ExecutionClient, diff --git a/relaykit/relayconvert/internal/toolconv/encode.go b/relaykit/relayconvert/internal/toolconv/encode.go index b2e60132ab..a653609a20 100644 --- a/relaykit/relayconvert/internal/toolconv/encode.go +++ b/relaykit/relayconvert/internal/toolconv/encode.go @@ -1322,14 +1322,14 @@ func deleteEmptyStrings(value map[string]any) { } } -func functionParametersMap(parameters any) (map[string]interface{}, error) { +func functionParametersMap(parameters any) (map[string]any, error) { if parameters == nil { - return map[string]interface{}{ + return map[string]any{ "type": "object", - "properties": map[string]interface{}{}, + "properties": map[string]any{}, }, nil } - converted, err := kitutil.Any2Type[map[string]interface{}](parameters) + converted, err := kitutil.Any2Type[map[string]any](parameters) if err != nil { return nil, err } @@ -1337,7 +1337,7 @@ func functionParametersMap(parameters any) (map[string]interface{}, error) { converted["type"] = "object" } if converted["properties"] == nil { - converted["properties"] = map[string]interface{}{} + converted["properties"] = map[string]any{} } return converted, nil } diff --git a/relaykit/relayconvert/kitutil/mask.go b/relaykit/relayconvert/kitutil/mask.go index d193a56e84..283fbfec57 100644 --- a/relaykit/relayconvert/kitutil/mask.go +++ b/relaykit/relayconvert/kitutil/mask.go @@ -48,10 +48,7 @@ func maskHostForPlainDomain(domain string) string { return domain } tail := maskHostTail(parts) - numStars := len(parts) - len(tail) - if numStars < 1 { - numStars = 1 - } + numStars := max(len(parts)-len(tail), 1) stars := strings.TrimSuffix(strings.Repeat("***.", numStars), ".") return stars + "." + strings.Join(tail, ".") } diff --git a/relaykit/relayconvert/kitutil/value.go b/relaykit/relayconvert/kitutil/value.go index 745795cb23..0aaf72cb16 100644 --- a/relaykit/relayconvert/kitutil/value.go +++ b/relaykit/relayconvert/kitutil/value.go @@ -13,7 +13,7 @@ func GetPointer[T any](v T) *T { return &v } -func Interface2String(inter interface{}) string { +func Interface2String(inter any) string { switch inter.(type) { case string: return inter.(string) diff --git a/relaykit/relayconvert/reasoning/claude.go b/relaykit/relayconvert/reasoning/claude.go index 44565a113c..ad1572dc94 100644 --- a/relaykit/relayconvert/reasoning/claude.go +++ b/relaykit/relayconvert/reasoning/claude.go @@ -240,10 +240,7 @@ func RenderClaude(model string, intent Intent, maxTokens *uint, adapterBudgetPer budget := 0 if intent.BudgetTokens != nil && *intent.BudgetTokens >= 0 { requestedBudget := *intent.BudgetTokens - budget = requestedBudget - if budget < 1024 { - budget = 1024 - } + budget = max(requestedBudget, 1024) if uint(budget) >= *maxTokens { budget = int(*maxTokens) - 1 } @@ -261,10 +258,7 @@ func RenderClaude(model string, intent Intent, maxTokens *uint, adapterBudgetPer )) } percentage := effortPercentage(intent.Effort, adapterBudgetPercentage) - budget = int(*maxTokens) * percentage / 100 - if budget < 1024 { - budget = 1024 - } + budget = max(int(*maxTokens)*percentage/100, 1024) if uint(budget) >= *maxTokens { budget = int(*maxTokens) - 1 } diff --git a/relaykit/relayconvert/reasoning/suffix.go b/relaykit/relayconvert/reasoning/suffix.go index 558e12e4d7..1cb9a0cc0a 100644 --- a/relaykit/relayconvert/reasoning/suffix.go +++ b/relaykit/relayconvert/reasoning/suffix.go @@ -232,12 +232,12 @@ func parseProviderModelSuffix(modelName string, requiredPrefix string, allowThin } return baseModel, intent, true, nil } - if strings.HasSuffix(modelName, "-nothinking") { - baseModel := strings.TrimSuffix(modelName, "-nothinking") + if before, ok := strings.CutSuffix(modelName, "-nothinking"); ok { + baseModel := before return baseModel, Intent{Mode: ModeDisabled, Effort: EffortNone, Source: SourceSuffix}, true, nil } - if strings.HasSuffix(modelName, "-thinking") { - baseModel := strings.TrimSuffix(modelName, "-thinking") + if before, ok := strings.CutSuffix(modelName, "-thinking"); ok { + baseModel := before intent := Intent{Mode: ModeEnabled, Source: SourceSuffix} if includeThoughts { value := true diff --git a/relaykit/relayconvert/response_registry_test.go b/relaykit/relayconvert/response_registry_test.go index 866cc4ea34..150de1ecb7 100644 --- a/relaykit/relayconvert/response_registry_test.go +++ b/relaykit/relayconvert/response_registry_test.go @@ -205,7 +205,7 @@ func TestConvertResponseDirectAndMultiHopConverters(t *testing.T) { assert.Equal(t, "text", claudeValue.Content[0].Type) assert.Equal(t, "tool_use", claudeValue.Content[1].Type) assert.Equal(t, "lookup", claudeValue.Content[1].Name) - assert.Equal(t, map[string]interface{}{"q": "x"}, claudeValue.Content[1].Input) + assert.Equal(t, map[string]any{"q": "x"}, claudeValue.Content[1].Input) assert.Equal(t, 11, toClaude.Usage.TotalTokens) toGemini, err := ConvertResponse(nil, &convmeta.Values{ChannelMetaAttached: true, UpstreamModelName: "gemini-test"}, types.RelayFormatGemini, responses) @@ -223,7 +223,7 @@ func TestConvertResponseDirectAndMultiHopConverters(t *testing.T) { assert.Equal(t, "hello", geminiValue.Candidates[0].Content.Parts[0].Text) require.NotNil(t, geminiValue.Candidates[0].Content.Parts[1].FunctionCall) assert.Equal(t, "lookup", geminiValue.Candidates[0].Content.Parts[1].FunctionCall.FunctionName) - assert.Equal(t, map[string]interface{}{"q": "x"}, geminiValue.Candidates[0].Content.Parts[1].FunctionCall.Arguments) + assert.Equal(t, map[string]any{"q": "x"}, geminiValue.Candidates[0].Content.Parts[1].FunctionCall.Arguments) assert.Equal(t, 11, toGemini.Usage.TotalTokens) } @@ -284,7 +284,7 @@ func TestConvertResponseProviderToOAIChatUsage(t *testing.T) { Model: "claude-test", StopReason: "end_turn", Content: []dto.ClaudeMediaMessage{ - {Type: "tool_use", Id: "toolu_1", Name: "lookup", Input: map[string]interface{}{"q": "x"}}, + {Type: "tool_use", Id: "toolu_1", Name: "lookup", Input: map[string]any{"q": "x"}}, }, Usage: &dto.ClaudeUsage{ InputTokens: 10, @@ -326,7 +326,7 @@ func TestConvertResponseProviderToOAIChatUsage(t *testing.T) { Content: dto.GeminiChatContent{ Parts: []dto.GeminiPart{ {Text: "hello"}, - {FunctionCall: &dto.FunctionCall{FunctionName: "lookup", Arguments: map[string]interface{}{"q": "x"}}}, + {FunctionCall: &dto.FunctionCall{FunctionName: "lookup", Arguments: map[string]any{"q": "x"}}}, }, }, }, diff --git a/router/plugin-router.go b/router/plugin-router.go index f90a43ba41..1ec24a8abe 100644 --- a/router/plugin-router.go +++ b/router/plugin-router.go @@ -542,11 +542,8 @@ func routePatternsIntersect(leftPath, rightPath string) bool { func routesGinCompatible(leftPath, rightPath string) bool { left := parseRoutePattern(leftPath) right := parseRoutePattern(rightPath) - limit := len(left) - if len(right) < limit { - limit = len(right) - } - for index := 0; index < limit; index++ { + limit := min(len(right), len(left)) + for index := range limit { leftSegment := left[index] rightSegment := right[index] if !leftSegment.dynamic && !rightSegment.dynamic { diff --git a/service/auth_session.go b/service/auth_session.go index 460b5a91b8..eaf808bc87 100644 --- a/service/auth_session.go +++ b/service/auth_session.go @@ -312,10 +312,7 @@ func WriteRefreshCookie(c *gin.Context, rawToken string) { expiresAt = time.Unix(session.ExpiresAt, 0) } } - maxAge := int(time.Until(expiresAt) / time.Second) - if maxAge < 1 { - maxAge = 1 - } + maxAge := max(int(time.Until(expiresAt)/time.Second), 1) http.SetCookie(c.Writer, &http.Cookie{ Name: RefreshCookieName, Value: rawToken, diff --git a/service/auth_session_test.go b/service/auth_session_test.go index 5342ff4fcd..f1c91ff545 100644 --- a/service/auth_session_test.go +++ b/service/auth_session_test.go @@ -102,7 +102,7 @@ func TestCreateLoginSessionEnforcesActiveLimitAcrossAuthVersions(t *testing.T) { common.UserSessionIssuanceLimit = 100 now := time.Now().Unix() rows := make([]model.UserSession, 0, 49) - for i := 0; i < 49; i++ { + for i := range 49 { authVersion := user.AuthVersion if i == 0 { authVersion++ @@ -216,7 +216,7 @@ func TestCleanupAuthArtifactsAlertsBeforeDeletingHourlyIssuance(t *testing.T) { common.UserSessionIssuanceWindowSeconds = 1 now := time.Now() boundaryRows := make([]model.UserSession, 0, 2) - for i := 0; i < 2; i++ { + for i := range 2 { boundaryRows = append(boundaryRows, model.UserSession{ SID: "hourly-boundary-" + string(rune('a'+i)), UserID: 1, Version: 1, UserAuthVersion: 1, Status: model.UserSessionStatusActive, RefreshHash: "hash", LoginMethod: "password", @@ -243,7 +243,7 @@ func TestCleanupAuthArtifactsAlertsBeforeDeletingHourlyIssuance(t *testing.T) { assert.Zero(t, count) exceededRows := make([]model.UserSession, 0, 3) - for i := 0; i < 3; i++ { + for i := range 3 { exceededRows = append(exceededRows, model.UserSession{ SID: "hourly-exceeded-" + string(rune('a'+i)), UserID: 1, Version: 1, UserAuthVersion: 1, Status: model.UserSessionStatusActive, RefreshHash: "hash", LoginMethod: "password", diff --git a/service/auth_token.go b/service/auth_token.go index b6ea1df929..4fa5e48e9d 100644 --- a/service/auth_token.go +++ b/service/auth_token.go @@ -5,6 +5,7 @@ import ( "crypto/sha256" "errors" "fmt" + "slices" "strconv" "strings" "time" @@ -113,13 +114,7 @@ func ParseDashboardAccessToken(raw string) (identity AuthIdentity, internal bool if parseErr != nil || parsed == nil { return AuthIdentity{}, false, nil } - audienceMatches := false - for _, audience := range claims.Audience { - if audience == authTokenAudience { - audienceMatches = true - break - } - } + audienceMatches := slices.Contains(claims.Audience, authTokenAudience) knownTokenUse := claims.TokenUse == accessTokenUse || claims.TokenUse == securityProofTokenUse if claims.Issuer != authTokenIssuer || !audienceMatches || !knownTokenUse { return AuthIdentity{}, false, nil diff --git a/service/authz/adapter.go b/service/authz/adapter.go index 6c971a8aad..4a2484c4d0 100644 --- a/service/authz/adapter.go +++ b/service/authz/adapter.go @@ -83,7 +83,7 @@ func (a *gormAdapter) RemoveFilteredPolicy(_ string, ptype string, fieldIndex in func (a *gormAdapter) ruleQuery(query *gorm.DB, ptype string, rule []string) *gorm.DB { query = query.Where("ptype = ?", ptype) - for idx := 0; idx < 6; idx++ { + for idx := range 6 { value := "" if idx < len(rule) { value = rule[idx] diff --git a/service/authz/registry.go b/service/authz/registry.go index 2b158d0529..6a44fd601d 100644 --- a/service/authz/registry.go +++ b/service/authz/registry.go @@ -1,5 +1,7 @@ package authz +import "slices" + // ActionDefinition describes a single action exposed by a resource. DefaultRoles // lists the role keys that receive this action as part of their baseline grants. type ActionDefinition struct { @@ -67,12 +69,7 @@ func PermissionsForRole(roleKey string) []Permission { } func actionHasRole(action ActionDefinition, roleKey string) bool { - for _, r := range action.DefaultRoles { - if r == roleKey { - return true - } - } - return false + return slices.Contains(action.DefaultRoles, roleKey) } func isKnownResource(resource string) bool { diff --git a/service/authz/resolver.go b/service/authz/resolver.go index 888c5fb08d..854b4fb3f6 100644 --- a/service/authz/resolver.go +++ b/service/authz/resolver.go @@ -1,5 +1,7 @@ package authz +import "slices" + import "github.com/casbin/casbin/v2" // Can reports whether the subject may perform the permission. A superuser role @@ -10,10 +12,8 @@ func Can(userID int, systemRole int, permission Permission) bool { if len(roles) == 0 { return false } - for _, role := range roles { - if isSuperuserRole(role) { - return true - } + if slices.ContainsFunc(roles, isSuperuserRole) { + return true } if !isKnownPermission(permission) { return false diff --git a/service/channel_affinity.go b/service/channel_affinity.go index acaa4d6b28..ac61653587 100644 --- a/service/channel_affinity.go +++ b/service/channel_affinity.go @@ -3,6 +3,7 @@ package service import ( "fmt" "hash/fnv" + "maps" "regexp" "strconv" "strings" @@ -46,7 +47,7 @@ type channelAffinityMeta struct { TTLSeconds int RuleName string SkipRetry bool - ParamTemplate map[string]interface{} + ParamTemplate map[string]any KeySourceType string KeySourceKey string KeySourcePath string @@ -435,20 +436,18 @@ func buildChannelAffinityKeyHint(s string) string { return s[:4] + "..." + s[len(s)-4:] } -func cloneStringAnyMap(src map[string]interface{}) map[string]interface{} { +func cloneStringAnyMap(src map[string]any) map[string]any { if len(src) == 0 { - return map[string]interface{}{} - } - dst := make(map[string]interface{}, len(src)) - for k, v := range src { - dst[k] = v + return map[string]any{} } + dst := make(map[string]any, len(src)) + maps.Copy(dst, src) return dst } -func mergeChannelOverride(base map[string]interface{}, tpl map[string]interface{}) map[string]interface{} { +func mergeChannelOverride(base map[string]any, tpl map[string]any) map[string]any { if len(base) == 0 && len(tpl) == 0 { - return map[string]interface{}{} + return map[string]any{} } if len(tpl) == 0 { return base @@ -475,17 +474,17 @@ func mergeChannelOverride(base map[string]interface{}, tpl map[string]interface{ return out } -func extractParamOperations(value interface{}) ([]interface{}, bool) { +func extractParamOperations(value any) ([]any, bool) { switch ops := value.(type) { - case []interface{}: + case []any: if len(ops) == 0 { - return []interface{}{}, true + return []any{}, true } - cloned := make([]interface{}, 0, len(ops)) + cloned := make([]any, 0, len(ops)) cloned = append(cloned, ops...) return cloned, true - case []map[string]interface{}: - cloned := make([]interface{}, 0, len(ops)) + case []map[string]any: + cloned := make([]any, 0, len(ops)) for _, op := range ops { cloned = append(cloned, op) } @@ -503,19 +502,19 @@ func appendChannelAffinityTemplateAdminInfo(c *gin.Context, meta channelAffinity return } - templateInfo := map[string]interface{}{ + templateInfo := map[string]any{ "applied": true, "rule_name": meta.RuleName, "param_override_keys": len(meta.ParamTemplate), } if anyInfo, ok := c.Get(ginKeyChannelAffinityLogInfo); ok { - if info, ok := anyInfo.(map[string]interface{}); ok { + if info, ok := anyInfo.(map[string]any); ok { info["override_template"] = templateInfo c.Set(ginKeyChannelAffinityLogInfo, info) return } } - c.Set(ginKeyChannelAffinityLogInfo, map[string]interface{}{ + c.Set(ginKeyChannelAffinityLogInfo, map[string]any{ "reason": meta.RuleName, "rule_name": meta.RuleName, "using_group": meta.UsingGroup, @@ -531,7 +530,7 @@ func appendChannelAffinityTemplateAdminInfo(c *gin.Context, meta channelAffinity } // ApplyChannelAffinityOverrideTemplate merges per-rule channel override templates onto the selected channel override config. -func ApplyChannelAffinityOverrideTemplate(c *gin.Context, paramOverride map[string]interface{}) (map[string]interface{}, bool) { +func ApplyChannelAffinityOverrideTemplate(c *gin.Context, paramOverride map[string]any) (map[string]any, bool) { if c == nil { return paramOverride, false } @@ -683,7 +682,7 @@ func MarkChannelAffinityUsed(c *gin.Context, selectedGroup string, channelID int return } c.Set(ginKeyChannelAffinitySkipRetry, meta.SkipRetry) - info := map[string]interface{}{ + info := map[string]any{ "reason": meta.RuleName, "rule_name": meta.RuleName, "using_group": meta.UsingGroup, diff --git a/service/channel_affinity_template_test.go b/service/channel_affinity_template_test.go index fb703a24e7..f5f61f293c 100644 --- a/service/channel_affinity_template_test.go +++ b/service/channel_affinity_template_test.go @@ -25,7 +25,7 @@ func TestApplyChannelAffinityOverrideTemplate_NoTemplate(t *testing.T) { ctx := buildChannelAffinityTemplateContextForTest(channelAffinityMeta{ RuleName: "rule-no-template", }) - base := map[string]interface{}{ + base := map[string]any{ "temperature": 0.7, } @@ -37,7 +37,7 @@ func TestApplyChannelAffinityOverrideTemplate_NoTemplate(t *testing.T) { func TestApplyChannelAffinityOverrideTemplate_MergeTemplate(t *testing.T) { ctx := buildChannelAffinityTemplateContextForTest(channelAffinityMeta{ RuleName: "rule-with-template", - ParamTemplate: map[string]interface{}{ + ParamTemplate: map[string]any{ "temperature": 0.2, "top_p": 0.95, }, @@ -49,7 +49,7 @@ func TestApplyChannelAffinityOverrideTemplate_MergeTemplate(t *testing.T) { KeyHint: "abcd...wxyz", KeyFingerprint: "abcd1234", }) - base := map[string]interface{}{ + base := map[string]any{ "temperature": 0.7, "max_tokens": 2000, } @@ -63,11 +63,11 @@ func TestApplyChannelAffinityOverrideTemplate_MergeTemplate(t *testing.T) { anyInfo, ok := ctx.Get(ginKeyChannelAffinityLogInfo) require.True(t, ok) - info, ok := anyInfo.(map[string]interface{}) + info, ok := anyInfo.(map[string]any) require.True(t, ok) overrideInfoAny, ok := info["override_template"] require.True(t, ok) - overrideInfo, ok := overrideInfoAny.(map[string]interface{}) + overrideInfo, ok := overrideInfoAny.(map[string]any) require.True(t, ok) require.Equal(t, true, overrideInfo["applied"]) require.Equal(t, "rule-with-template", overrideInfo["rule_name"]) @@ -77,8 +77,8 @@ func TestApplyChannelAffinityOverrideTemplate_MergeTemplate(t *testing.T) { func TestApplyChannelAffinityOverrideTemplate_MergeOperations(t *testing.T) { ctx := buildChannelAffinityTemplateContextForTest(channelAffinityMeta{ RuleName: "rule-with-ops-template", - ParamTemplate: map[string]interface{}{ - "operations": []map[string]interface{}{ + ParamTemplate: map[string]any{ + "operations": []map[string]any{ { "mode": "pass_headers", "value": []string{"Originator"}, @@ -86,9 +86,9 @@ func TestApplyChannelAffinityOverrideTemplate_MergeOperations(t *testing.T) { }, }, }) - base := map[string]interface{}{ + base := map[string]any{ "temperature": 0.7, - "operations": []map[string]interface{}{ + "operations": []map[string]any{ { "path": "model", "mode": "trim_prefix", @@ -103,15 +103,15 @@ func TestApplyChannelAffinityOverrideTemplate_MergeOperations(t *testing.T) { opsAny, ok := merged["operations"] require.True(t, ok) - ops, ok := opsAny.([]interface{}) + ops, ok := opsAny.([]any) require.True(t, ok) require.Len(t, ops, 2) - firstOp, ok := ops[0].(map[string]interface{}) + firstOp, ok := ops[0].(map[string]any) require.True(t, ok) require.Equal(t, "pass_headers", firstOp["mode"]) - secondOp, ok := ops[1].(map[string]interface{}) + secondOp, ok := ops[1].(map[string]any) require.True(t, ok) require.Equal(t, "trim_prefix", secondOp["mode"]) } @@ -297,7 +297,7 @@ func TestChannelAffinityHitCodexTemplatePassHeadersEffective(t *testing.T) { require.True(t, found) require.Equal(t, 9527, channelID) - baseOverride := map[string]interface{}{ + baseOverride := map[string]any{ "temperature": 0.2, } mergedOverride, applied := ApplyChannelAffinityOverrideTemplate(ctx, baseOverride) @@ -312,7 +312,7 @@ func TestChannelAffinityHitCodexTemplatePassHeadersEffective(t *testing.T) { }, ChannelMeta: &relaycommon.ChannelMeta{ ParamOverride: mergedOverride, - HeadersOverride: map[string]interface{}{ + HeadersOverride: map[string]any{ "X-Static": "legacy-static", }, }, diff --git a/service/email_binding.go b/service/email_binding.go index 61754c06cf..979d62d2b8 100644 --- a/service/email_binding.go +++ b/service/email_binding.go @@ -6,6 +6,7 @@ import ( "fmt" "html" "math/big" + "slices" "strings" "time" @@ -41,13 +42,7 @@ func ValidateAccountEmail(email string) (string, error) { return "", ErrAccountEmailInvalid } if common.EmailDomainRestrictionEnabled { - allowed := false - for _, domain := range common.EmailDomainWhitelist { - if parts[1] == domain { - allowed = true - break - } - } + allowed := slices.Contains(common.EmailDomainWhitelist, parts[1]) if !allowed { return "", ErrAccountEmailRestricted } diff --git a/service/error_test.go b/service/error_test.go index 266d2a8755..382a9ade0f 100644 --- a/service/error_test.go +++ b/service/error_test.go @@ -51,7 +51,6 @@ func TestResetStatusCode(t *testing.T) { } for _, tc := range testCases { - tc := tc t.Run(tc.name, func(t *testing.T) { t.Parallel() diff --git a/service/file_decoder.go b/service/file_decoder.go index 18376ccbaa..0ef3af3059 100644 --- a/service/file_decoder.go +++ b/service/file_decoder.go @@ -43,8 +43,8 @@ func GetFileTypeFromUrl(c *gin.Context, url string, reason ...string) (string, e } if cd := response.Header.Get("Content-Disposition"); cd != "" { - parts := strings.Split(cd, ";") - for _, part := range parts { + parts := strings.SplitSeq(cd, ";") + for part := range parts { part = strings.TrimSpace(part) if strings.HasPrefix(strings.ToLower(part), "filename=") { name := strings.TrimSpace(strings.TrimPrefix(part, "filename=")) diff --git a/service/file_service.go b/service/file_service.go index 52652a3478..6a6b404602 100644 --- a/service/file_service.go +++ b/service/file_service.go @@ -258,8 +258,8 @@ func smartDetectMimeType(resp *http.Response, url string, fileBytes []byte) stri // 2. 尝试从 Content-Disposition header 的 filename 获取 if cd := resp.Header.Get("Content-Disposition"); cd != "" { - parts := strings.Split(cd, ";") - for _, part := range parts { + parts := strings.SplitSeq(cd, ";") + for part := range parts { part = strings.TrimSpace(part) if strings.HasPrefix(strings.ToLower(part), "filename=") { name := strings.TrimSpace(strings.TrimPrefix(part, "filename=")) @@ -322,10 +322,10 @@ func loadFromBase64(base64String string, providedMimeType string) (*types.Cached // 处理 data: 前缀 if strings.HasPrefix(base64String, "data:") { - idx := strings.Index(base64String, ",") - if idx != -1 { - header := base64String[:idx] - cleanBase64 = base64String[idx+1:] + before, after, ok := strings.Cut(base64String, ",") + if ok { + header := before + cleanBase64 = after if strings.Contains(header, ":") && strings.Contains(header, ";") { mimeStart := strings.Index(header, ":") + 1 diff --git a/service/funding_source.go b/service/funding_source.go index 7045704b9e..e4a356b5e7 100644 --- a/service/funding_source.go +++ b/service/funding_source.go @@ -135,7 +135,7 @@ func refundWithRetry(fn func() error) error { } const maxAttempts = 3 var lastErr error - for i := 0; i < maxAttempts; i++ { + for i := range maxAttempts { if err := fn(); err == nil { return nil } else { diff --git a/service/group.go b/service/group.go index e792083e4a..b01da23cfb 100644 --- a/service/group.go +++ b/service/group.go @@ -18,13 +18,13 @@ func GetUserUsableGroups(userGroup string) map[string]string { if b { // 处理特殊可用分组 for specialGroup, desc := range specialSettings { - if strings.HasPrefix(specialGroup, "-:") { + if after, ok := strings.CutPrefix(specialGroup, "-:"); ok { // 移除分组 - groupToRemove := strings.TrimPrefix(specialGroup, "-:") + groupToRemove := after delete(groupsCopy, groupToRemove) - } else if strings.HasPrefix(specialGroup, "+:") { + } else if after, ok := strings.CutPrefix(specialGroup, "+:"); ok { // 添加分组 - groupToAdd := strings.TrimPrefix(specialGroup, "+:") + groupToAdd := after groupsCopy[groupToAdd] = desc } else { // 直接添加分组 diff --git a/service/http_client_transport_test.go b/service/http_client_transport_test.go index b2f83a1a02..7fc87bb95a 100644 --- a/service/http_client_transport_test.go +++ b/service/http_client_transport_test.go @@ -52,13 +52,13 @@ func TestShardedRoundTripperPerOriginRotation(t *testing.T) { originB := "https://b.example:443" gotA := make([]uint32, 0, 8) - for i := 0; i < 8; i++ { + for range 8 { gotA = append(gotA, s.pickShard(originA)) } assert.Equal(t, []uint32{0, 1, 2, 3, 0, 1, 2, 3}, gotA) gotB := make([]uint32, 0, 4) - for i := 0; i < 4; i++ { + for range 4 { gotB = append(gotB, s.pickShard(originB)) } assert.Equal(t, []uint32{0, 1, 2, 3}, gotB, "independent origins must have independent counters") @@ -68,10 +68,10 @@ func TestShardedRoundTripperPerOriginRotation(t *testing.T) { const perWorker = 50 var badShardCount atomic.Uint32 wg.Add(workers) - for i := 0; i < workers; i++ { + for range workers { go func() { defer wg.Done() - for j := 0; j < perWorker; j++ { + for range perWorker { idx := s.pickShard(originA) if idx >= 4 { badShardCount.Add(1) @@ -132,7 +132,7 @@ func TestAutoOneShardNegotiatesHTTP2SingleConnection(t *testing.T) { })) client := newHTTPClientWithPolicyAndTLS(defaultHTTPTransportPolicy(), testTLSClientConfig(t, server)) - for i := 0; i < 4; i++ { + for range 4 { resp, err := client.Get(server.URL) require.NoError(t, err) assert.Equal(t, 2, resp.ProtoMajor) @@ -165,7 +165,7 @@ func TestFourShardHTTP2ReusesExactlyFourConnections(t *testing.T) { policy := HTTPTransportPolicy{Protocol: dto.HTTPProtocolAuto, Shards: 4} client := newHTTPClientWithPolicyAndTLS(policy, testTLSClientConfig(t, server)) - for i := 0; i < 8; i++ { + for range 8 { resp, err := client.Get(server.URL) require.NoError(t, err) assert.Equal(t, 2, resp.ProtoMajor) @@ -233,7 +233,7 @@ func TestForcedHTTP1ConcurrentDistinctConnections(t *testing.T) { client := newHTTPClientWithPolicyAndTLS(policy, testTLSClientConfig(t, server)) errCh := make(chan error, k) - for i := 0; i < k; i++ { + for range k { go func() { resp, err := client.Get(server.URL) if err != nil { @@ -251,7 +251,7 @@ func TestForcedHTTP1ConcurrentDistinctConnections(t *testing.T) { }() } - for i := 0; i < k; i++ { + for range k { <-arrived } mu.Lock() @@ -259,7 +259,7 @@ func TestForcedHTTP1ConcurrentDistinctConnections(t *testing.T) { mu.Unlock() close(release) - for i := 0; i < k; i++ { + for range k { require.NoError(t, <-errCh) } assert.Equal(t, uint32(0), nonHTTP1Count.Load()) @@ -308,7 +308,7 @@ func TestHTTPClientCacheConcurrentGetOrCreate(t *testing.T) { errs := make([]error, workers) var wg sync.WaitGroup wg.Add(workers) - for i := 0; i < workers; i++ { + for i := range workers { i := i go func() { defer wg.Done() @@ -318,7 +318,7 @@ func TestHTTPClientCacheConcurrentGetOrCreate(t *testing.T) { }() } wg.Wait() - for i := 0; i < workers; i++ { + for i := range workers { require.NoError(t, errs[i]) } for i := 1; i < workers; i++ { @@ -433,7 +433,7 @@ func TestResetProxyClientCacheConcurrentWithGetHttpClient(t *testing.T) { const workers = 64 var wg sync.WaitGroup wg.Add(workers * 2) - for i := 0; i < workers; i++ { + for range workers { go func() { defer wg.Done() _ = GetHttpClient() diff --git a/service/http_transport_sharded.go b/service/http_transport_sharded.go index d557c58185..5e8341b9e0 100644 --- a/service/http_transport_sharded.go +++ b/service/http_transport_sharded.go @@ -23,10 +23,7 @@ type shardedRoundTripper struct { } func newShardedRoundTripper(policy HTTPTransportPolicy, factory func() *http.Transport) *shardedRoundTripper { - n := policy.Shards - if n < 1 { - n = 1 - } + n := max(policy.Shards, 1) shards := make([]http.RoundTripper, n) for i := 0; i < n; i++ { transport := factory() diff --git a/service/log_info_generate.go b/service/log_info_generate.go index aec98ce9d0..ab21e18529 100644 --- a/service/log_info_generate.go +++ b/service/log_info_generate.go @@ -144,7 +144,7 @@ func appendStreamStatus(relayInfo *relaycommon.RelayInfo, other *model.LogOther) if !ss.IsNormalEnd() || ss.HasErrors() { status = "error" } - streamInfo := map[string]interface{}{ + streamInfo := map[string]any{ "status": status, "end_reason": string(ss.EndReason), } @@ -200,10 +200,7 @@ func appendBillingInfo(relayInfo *relaycommon.RelayInfo, other *model.LogOther) usedFinal = 0 } if relayInfo.SubscriptionAmountTotal > 0 { - remain := relayInfo.SubscriptionAmountTotal - usedFinal - if remain < 0 { - remain = 0 - } + remain := max(relayInfo.SubscriptionAmountTotal-usedFinal, 0) other.SetPublic("subscription_total", relayInfo.SubscriptionAmountTotal) other.SetPublic("subscription_used", usedFinal) other.SetPublic("subscription_remain", remain) diff --git a/service/midjourney.go b/service/midjourney.go index 9f0b847094..2276951028 100644 --- a/service/midjourney.go +++ b/service/midjourney.go @@ -278,7 +278,7 @@ func DoMidjourneyHttpRequest(c *gin.Context, timeout time.Duration, fullRequestU //var requestBody io.Reader //requestBody = c.Request.Body // read request body to json, delete accountFilter and notifyHook - var mapResult map[string]interface{} + var mapResult map[string]any // if get request, no need to read request body if c.Request.Method != "GET" { err := json.NewDecoder(c.Request.Body).Decode(&mapResult) diff --git a/service/notify-limit.go b/service/notify-limit.go index cad5d7bc18..befc4e80be 100644 --- a/service/notify-limit.go +++ b/service/notify-limit.go @@ -33,7 +33,7 @@ func startCleanupTask() { for { time.Sleep(time.Hour) now := time.Now() - notifyLimitStore.Range(func(key, value interface{}) bool { + notifyLimitStore.Range(func(key, value any) bool { if limit, ok := value.(limitCount); ok { if now.Sub(limit.Timestamp) >= getDuration() { notifyLimitStore.Delete(key) diff --git a/service/quota.go b/service/quota.go index 9080a1f91c..2de41ca8f7 100644 --- a/service/quota.go +++ b/service/quota.go @@ -489,7 +489,7 @@ func checkAndSendQuotaNotify(relayInfo *relaycommon.RelayInfo, quota int, preCon // 根据通知方式生成不同的内容格式 var content string - var values []interface{} + var values []any notifyType := userSetting.NotifyType if notifyType == "" { @@ -499,14 +499,14 @@ func checkAndSendQuotaNotify(relayInfo *relaycommon.RelayInfo, quota int, preCon if notifyType == dto.NotifyTypeBark { // Bark推送使用简短文本,不支持HTML content = "{{value}},剩余额度:{{value}},请及时充值" - values = []interface{}{prompt, logger.FormatQuota(relayInfo.UserQuota)} + values = []any{prompt, logger.FormatQuota(relayInfo.UserQuota)} } else if notifyType == dto.NotifyTypeGotify { content = "{{value}},当前剩余额度为 {{value}},请及时充值。" - values = []interface{}{prompt, logger.FormatQuota(relayInfo.UserQuota)} + values = []any{prompt, logger.FormatQuota(relayInfo.UserQuota)} } else { // 默认内容格式,适用于Email和Webhook(支持HTML) content = "{{value}},当前剩余额度为 {{value}},为了不影响您的使用,请及时充值。
充值链接:{{value}}" - values = []interface{}{prompt, logger.FormatQuota(relayInfo.UserQuota), topUpLink, topUpLink} + values = []any{prompt, logger.FormatQuota(relayInfo.UserQuota), topUpLink, topUpLink} } err := NotifyUser(relayInfo.UserId, relayInfo.UserEmail, relayInfo.UserSetting, dto.NewNotify(dto.NotifyTypeQuotaExceed, prompt, content, values)) @@ -542,7 +542,7 @@ func checkAndSendSubscriptionQuotaNotify(relayInfo *relaycommon.RelayInfo) { topUpLink := PaymentReturnURL("/wallet") var content string - var values []interface{} + var values []any notifyType := userSetting.NotifyType if notifyType == "" { notifyType = dto.NotifyTypeEmail @@ -550,13 +550,13 @@ func checkAndSendSubscriptionQuotaNotify(relayInfo *relaycommon.RelayInfo) { if notifyType == dto.NotifyTypeBark { content = "{{value}},剩余额度:{{value}},请及时充值" - values = []interface{}{prompt, logger.FormatQuota(int(remaining))} + values = []any{prompt, logger.FormatQuota(int(remaining))} } else if notifyType == dto.NotifyTypeGotify { content = "{{value}},当前剩余额度为 {{value}},请及时充值。" - values = []interface{}{prompt, logger.FormatQuota(int(remaining))} + values = []any{prompt, logger.FormatQuota(int(remaining))} } else { content = "{{value}},当前剩余额度为 {{value}},为了不影响您的使用,请及时充值。
充值链接:{{value}}" - values = []interface{}{prompt, logger.FormatQuota(int(remaining)), topUpLink, topUpLink} + values = []any{prompt, logger.FormatQuota(int(remaining)), topUpLink, topUpLink} } if err := NotifyUser(relayInfo.UserId, relayInfo.UserEmail, relayInfo.UserSetting, dto.NewNotify(dto.NotifyTypeQuotaExceed, prompt, content, values)); err != nil { diff --git a/service/quota_saturation_test.go b/service/quota_saturation_test.go index 6f25448bea..5be73c96d4 100644 --- a/service/quota_saturation_test.go +++ b/service/quota_saturation_test.go @@ -38,9 +38,9 @@ func TestAttachQuotaSaturationNestsUnderAdminInfo(t *testing.T) { other.SetPublic("model_price", 0.004) attachQuotaSaturation(ctx, relayInfo, other) - adminInfo, ok := other.Snapshot()["admin_info"].(map[string]interface{}) + adminInfo, ok := other.Snapshot()["admin_info"].(map[string]any) require.True(t, ok, "admin_info should be created") - sat, ok := adminInfo["quota_saturation"].(map[string]interface{}) + sat, ok := adminInfo["quota_saturation"].(map[string]any) require.True(t, ok, "quota_saturation should be nested under admin_info") require.Equal(t, "QuotaFromDecimal", sat["op"]) require.Equal(t, common.QuotaClampOverflow, sat["kind"]) @@ -82,7 +82,7 @@ func TestAttachQuotaSaturationPreservesExistingAdminInfo(t *testing.T) { other.SetAdmin("admin_username", "root") attachQuotaSaturation(ctx, relayInfo, other) - adminInfo := other.Snapshot()["admin_info"].(map[string]interface{}) + adminInfo := other.Snapshot()["admin_info"].(map[string]any) require.Equal(t, "root", adminInfo["admin_username"], "existing admin_info fields preserved") require.NotNil(t, adminInfo["quota_saturation"]) } diff --git a/service/rankings.go b/service/rankings.go index 462508583f..8b6aaed9c1 100644 --- a/service/rankings.go +++ b/service/rankings.go @@ -3,6 +3,7 @@ package service import ( "fmt" "math" + "slices" "sort" "sync" "time" @@ -516,9 +517,7 @@ func sortedRankingBuckets(bucketSet map[int64]struct{}) []int64 { for bucket := range bucketSet { buckets = append(buckets, bucket) } - sort.Slice(buckets, func(i, j int) bool { - return buckets[i] < buckets[j] - }) + slices.Sort(buckets) return buckets } diff --git a/service/system_instance.go b/service/system_instance.go index 37f5271518..58547e2f72 100644 --- a/service/system_instance.go +++ b/service/system_instance.go @@ -26,7 +26,7 @@ type SystemInstanceInfo struct { Role SystemInstanceRoleInfo `json:"role"` Runtime SystemInstanceRuntimeInfo `json:"runtime"` Host SystemInstanceHostInfo `json:"host"` - Resources SystemInstanceResources `json:"resources,omitempty"` + Resources SystemInstanceResources `json:"resources"` Extra map[string]any `json:"extra,omitempty"` } diff --git a/service/task_billing_test.go b/service/task_billing_test.go index fba0e84734..de49a24fa2 100644 --- a/service/task_billing_test.go +++ b/service/task_billing_test.go @@ -404,22 +404,22 @@ func TestTaskBillingOtherSeparatesPluginAndRootDiagnostics(t *testing.T) { other := taskBillingOther(task).Snapshot() assert.Equal(t, "task_public", other["task_id"]) - adminInfo, ok := other["admin_info"].(map[string]interface{}) + adminInfo, ok := other["admin_info"].(map[string]any) require.True(t, ok) - pluginInfo, ok := adminInfo["task_plugin"].(map[string]interface{}) + pluginInfo, ok := adminInfo["task_plugin"].(map[string]any) require.True(t, ok) assert.Equal(t, "document-parser", pluginInfo["key"]) assert.Equal(t, "1.2.3", pluginInfo["version"]) - assert.Equal(t, map[string]interface{}{ + assert.Equal(t, map[string]any{ "name": "Community Author", "url": "https://plugins.example/author", }, pluginInfo["author"]) - rootInfo, ok := other["root_info"].(map[string]interface{}) + rootInfo, ok := other["root_info"].(map[string]any) require.True(t, ok) assert.Equal(t, "upstream-private", rootInfo["upstream_task_id"]) assert.Equal(t, "node-a", rootInfo["node_name"]) - runtimeInfo, ok := rootInfo["task_plugin"].(map[string]interface{}) + runtimeInfo, ok := rootInfo["task_plugin"].(map[string]any) require.True(t, ok) assert.Equal(t, uint64(42), runtimeInfo["generation"]) assert.NotContains(t, runtimeInfo, "author") diff --git a/service/task_plugin_audit.go b/service/task_plugin_audit.go index ccfc88825d..cfd9a50cbd 100644 --- a/service/task_plugin_audit.go +++ b/service/task_plugin_audit.go @@ -55,20 +55,20 @@ func AppendTaskPluginAuditInfo(other *model.LogOther, snapshot *model.TaskPlugin if other == nil || snapshot == nil || snapshot.Key == "" { return } - taskPlugin := map[string]interface{}{ + taskPlugin := map[string]any{ "key": snapshot.Key, "name": snapshot.Name, "version": snapshot.Version, } if snapshot.Author != nil && snapshot.Author.Name != "" { - author := map[string]interface{}{"name": snapshot.Author.Name} + author := map[string]any{"name": snapshot.Author.Name} if snapshot.Author.URL != "" { author["url"] = snapshot.Author.URL } taskPlugin["author"] = author } other.SetAdmin("task_plugin", taskPlugin) - other.SetRoot("task_plugin", map[string]interface{}{ + other.SetRoot("task_plugin", map[string]any{ "key": snapshot.Key, "version": snapshot.Version, "api_version": snapshot.APIVersion, diff --git a/service/task_polling.go b/service/task_polling.go index 42b220caf0..f20f28daa0 100644 --- a/service/task_polling.go +++ b/service/task_polling.go @@ -4,6 +4,7 @@ import ( "context" "fmt" "io" + "maps" "net/http" "sort" "strings" @@ -670,12 +671,8 @@ func settleTaskBillingOnComplete(ctx context.Context, adaptor TaskPollingAdaptor return false } usageFacts := make(map[string]any, len(bc.TieredSnapshot.UsageFacts)+len(taskResult.UsageFacts)) - for key, value := range bc.TieredSnapshot.UsageFacts { - usageFacts[key] = value - } - for key, value := range taskResult.UsageFacts { - usageFacts[key] = value - } + maps.Copy(usageFacts, bc.TieredSnapshot.UsageFacts) + maps.Copy(usageFacts, taskResult.UsageFacts) result, err := billingexpr.ComputeTieredQuotaWithRequest(bc.TieredSnapshot, billingexpr.TokenParams{}, billingexpr.RequestInput{Usage: usageFacts}) if err != nil { logger.LogWarn(ctx, fmt.Sprintf("任务 %s 表达式结算失败,保留预扣额度: %v", task.TaskID, err)) diff --git a/service/text_quota.go b/service/text_quota.go index 83fe6ff3e8..2093be2513 100644 --- a/service/text_quota.go +++ b/service/text_quota.go @@ -319,10 +319,7 @@ func calculateTextQuotaSummary(ctx *gin.Context, relayInfo *relaycommon.RelayInf baseTokens = baseTokens.Sub(dCachedCreationTokens) cachedCreationTokensWithRatio = dCachedCreationTokens.Mul(dCacheCreationRatio) } else { - remaining := summary.CacheCreationTokens - summary.CacheCreationTokens5m - summary.CacheCreationTokens1h - if remaining < 0 { - remaining = 0 - } + remaining := max(summary.CacheCreationTokens-summary.CacheCreationTokens5m-summary.CacheCreationTokens1h, 0) cachedCreationTokensWithRatio = decimal.NewFromInt(int64(remaining)).Mul(dCacheCreationRatio) cachedCreationTokensWithRatio = cachedCreationTokensWithRatio.Add(decimal.NewFromInt(int64(summary.CacheCreationTokens5m)).Mul(dCacheCreationRatio5m)) cachedCreationTokensWithRatio = cachedCreationTokensWithRatio.Add(decimal.NewFromInt(int64(summary.CacheCreationTokens1h)).Mul(dCacheCreationRatio1h)) diff --git a/service/text_quota_test.go b/service/text_quota_test.go index da24cdcb3f..a93a35dbb0 100644 --- a/service/text_quota_test.go +++ b/service/text_quota_test.go @@ -451,13 +451,13 @@ func TestAppendUsageBillingPathForLogWritesAdminInfo(t *testing.T) { BillingUsage: dto.NewClaudeMessagesBillingUsage(&dto.ClaudeUsage{InputTokens: 1}), }) - adminInfo, ok := other.Snapshot()["admin_info"].(map[string]interface{}) + adminInfo, ok := other.Snapshot()["admin_info"].(map[string]any) require.True(t, ok) require.Equal(t, usageBillingPathAnthropic, adminInfo["usage_billing_path"]) other = model.NewLogOther() appendUsageBillingPathForLog(other, true, nil) - adminInfo, ok = other.Snapshot()["admin_info"].(map[string]interface{}) + adminInfo, ok = other.Snapshot()["admin_info"].(map[string]any) require.True(t, ok) require.Equal(t, usageBillingPathLocal, adminInfo["usage_billing_path"]) } diff --git a/service/token_counter.go b/service/token_counter.go index 369e97c33c..24d1cd494f 100644 --- a/service/token_counter.go +++ b/service/token_counter.go @@ -136,10 +136,7 @@ func getImageToken(c *gin.Context, fileMeta *types.FileMeta, model string, strea hScaled = float64(height) * r patchesW := math.Ceil(wScaled / 32.0) patchesH := math.Ceil(hScaled / 32.0) - imageTokens := int(patchesW * patchesH) - if imageTokens > 1536 { - imageTokens = 1536 - } + imageTokens := min(int(patchesW*patchesH), 1536) return common.QuotaRound(float64(imageTokens) * multiplier), nil } // below cap @@ -365,17 +362,17 @@ func CountTokenInput(input any, model string) int { case string: return CountTextToken(v, model) case []string: - text := "" + var text strings.Builder for _, s := range v { - text += s + text.WriteString(s) } - return CountTextToken(text, model) - case []interface{}: - text := "" + return CountTextToken(text.String(), model) + case []any: + var text strings.Builder for _, item := range v { - text += fmt.Sprintf("%v", item) + text.WriteString(fmt.Sprintf("%v", item)) } - return CountTextToken(text, model) + return CountTextToken(text.String(), model) } return CountTokenInput(fmt.Sprintf("%v", input), model) } diff --git a/service/violation_fee.go b/service/violation_fee.go index dba30ecdf9..e6b7340732 100644 --- a/service/violation_fee.go +++ b/service/violation_fee.go @@ -135,7 +135,7 @@ func ChargeViolationFeeIfNeeded(ctx *gin.Context, relayInfo *relaycommon.RelayIn oai := apiErr.ToOpenAIError() other := model.NewLogOther() - other.MergePublic(map[string]interface{}{ + other.MergePublic(map[string]any{ "violation_fee": true, "violation_fee_code": string(types.ErrorCodeViolationFeeGrokCSAM), "fee_quota": feeQuota, diff --git a/service/webhook.go b/service/webhook.go index 5d84e7da60..51e194dacf 100644 --- a/service/webhook.go +++ b/service/webhook.go @@ -16,11 +16,11 @@ import ( // WebhookPayload webhook 通知的负载数据 type WebhookPayload struct { - Type string `json:"type"` - Title string `json:"title"` - Content string `json:"content"` - Values []interface{} `json:"values,omitempty"` - Timestamp int64 `json:"timestamp"` + Type string `json:"type"` + Title string `json:"title"` + Content string `json:"content"` + Values []any `json:"values,omitempty"` + Timestamp int64 `json:"timestamp"` } // generateSignature 生成 webhook 签名 diff --git a/setting/auto_group.go b/setting/auto_group.go index 3b509b6026..cbab7a9697 100644 --- a/setting/auto_group.go +++ b/setting/auto_group.go @@ -2,6 +2,7 @@ package setting import ( "fmt" + "slices" "strconv" "sync/atomic" @@ -23,12 +24,7 @@ func init() { } func ContainsAutoGroup(group string) bool { - for _, autoGroup := range autoGroups { - if autoGroup == group { - return true - } - } - return false + return slices.Contains(autoGroups, group) } func UpdateAutoGroupsByJsonString(jsonString string) error { diff --git a/setting/billing_setting/tiered_billing.go b/setting/billing_setting/tiered_billing.go index 59df4f8076..b284f8d280 100644 --- a/setting/billing_setting/tiered_billing.go +++ b/setting/billing_setting/tiered_billing.go @@ -2,6 +2,7 @@ package billing_setting import ( "fmt" + "maps" "math" "sort" @@ -244,9 +245,7 @@ func taskUsageSmokeVectors(schema map[string]jsplugin.UsageFieldSchema) []map[st } if index == len(dimensions) { vector := make(map[string]any, len(current)) - for key, value := range current { - vector[key] = value - } + maps.Copy(vector, current) vectors = append(vectors, vector) return } diff --git a/setting/billing_setting/tiered_billing_test.go b/setting/billing_setting/tiered_billing_test.go index 1ce748a63e..8e78a11a37 100644 --- a/setting/billing_setting/tiered_billing_test.go +++ b/setting/billing_setting/tiered_billing_test.go @@ -5,9 +5,9 @@ import ( "testing" "github.com/QuantumNous/new-api/common" - "github.com/QuantumNous/new-api/relaykit/dto" "github.com/QuantumNous/new-api/pkg/jsplugin" relaycommon "github.com/QuantumNous/new-api/relay/common" + "github.com/QuantumNous/new-api/relaykit/dto" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -83,7 +83,7 @@ func TestSmokeTestTaskExprValidatesDeclaredUsageVectors(t *testing.T) { func TestSmokeTestTaskExprCapsOversizedEnumProductsAtLastCombination(t *testing.T) { schema := make(map[string]jsplugin.UsageFieldSchema, 7) condition := "" - for index := 0; index < 7; index++ { + for index := range 7 { schema[fmt.Sprintf("enum_%d", index)] = jsplugin.UsageFieldSchema{Enum: []string{"first", "middle", "last"}} if condition != "" { condition += " && " diff --git a/setting/config/config.go b/setting/config/config.go index a82d934f6e..6b1e7e7a04 100644 --- a/setting/config/config.go +++ b/setting/config/config.go @@ -12,7 +12,7 @@ import ( // ConfigManager 统一管理所有配置 type ConfigManager struct { - configs map[string]interface{} + configs map[string]any mutex sync.RWMutex } @@ -20,19 +20,19 @@ var GlobalConfig = NewConfigManager() func NewConfigManager() *ConfigManager { return &ConfigManager{ - configs: make(map[string]interface{}), + configs: make(map[string]any), } } // Register 注册一个配置模块 -func (cm *ConfigManager) Register(name string, config interface{}) { +func (cm *ConfigManager) Register(name string, config any) { cm.mutex.Lock() defer cm.mutex.Unlock() cm.configs[name] = config } // Get 获取指定配置模块 -func (cm *ConfigManager) Get(name string) interface{} { +func (cm *ConfigManager) Get(name string) any { cm.mutex.RLock() defer cm.mutex.RUnlock() return cm.configs[name] @@ -49,8 +49,8 @@ func (cm *ConfigManager) LoadFromDB(options map[string]string) error { // 收集属于此配置的所有选项 for key, value := range options { - if strings.HasPrefix(key, prefix) { - configKey := strings.TrimPrefix(key, prefix) + if after, ok := strings.CutPrefix(key, prefix); ok { + configKey := after configMap[configKey] = value } } @@ -90,11 +90,11 @@ func (cm *ConfigManager) SaveToDB(updateFunc func(key, value string) error) erro } // 辅助函数:将配置对象转换为map -func configToMap(config interface{}) (map[string]string, error) { +func configToMap(config any) (map[string]string, error) { result := make(map[string]string) val := reflect.ValueOf(config) - if val.Kind() == reflect.Ptr { + if val.Kind() == reflect.Pointer { val = val.Elem() } @@ -131,7 +131,7 @@ func configToMap(config interface{}) (map[string]string, error) { strValue = strconv.FormatUint(field.Uint(), 10) case reflect.Float32, reflect.Float64: strValue = strconv.FormatFloat(field.Float(), 'f', -1, 64) - case reflect.Ptr: + case reflect.Pointer: // 处理指针类型:如果非 nil,序列化指向的值 if !field.IsNil() { bytes, err := json.Marshal(field.Interface()) @@ -162,9 +162,9 @@ func configToMap(config interface{}) (map[string]string, error) { } // 辅助函数:从map更新配置对象 -func updateConfigFromMap(config interface{}, configMap map[string]string) error { +func updateConfigFromMap(config any, configMap map[string]string) error { val := reflect.ValueOf(config) - if val.Kind() != reflect.Ptr { + if val.Kind() != reflect.Pointer { return nil } val = val.Elem() @@ -237,7 +237,7 @@ func updateConfigFromMap(config interface{}, configMap map[string]string) error continue } field.SetFloat(floatValue) - case reflect.Ptr: + case reflect.Pointer: // 处理指针类型 if strValue == "null" { field.Set(reflect.Zero(field.Type())) @@ -273,12 +273,12 @@ func updateConfigFromMap(config interface{}, configMap map[string]string) error } // ConfigToMap 将配置对象转换为map(导出函数) -func ConfigToMap(config interface{}) (map[string]string, error) { +func ConfigToMap(config any) (map[string]string, error) { return configToMap(config) } // UpdateConfigFromMap 从map更新配置对象(导出函数) -func UpdateConfigFromMap(config interface{}, configMap map[string]string) error { +func UpdateConfigFromMap(config any, configMap map[string]string) error { return updateConfigFromMap(config, configMap) } diff --git a/setting/model_setting/claude.go b/setting/model_setting/claude.go index 2ce5d2c637..6998815118 100644 --- a/setting/model_setting/claude.go +++ b/setting/model_setting/claude.go @@ -68,7 +68,7 @@ func normalizeHeaderListValues(values []string) []string { normalizedValues := make([]string, 0, len(values)) seenValues := make(map[string]struct{}, len(values)) for _, value := range values { - for _, item := range strings.Split(value, ",") { + for item := range strings.SplitSeq(value, ",") { normalizedItem := strings.TrimSpace(item) if normalizedItem == "" { continue diff --git a/setting/model_setting/gemini.go b/setting/model_setting/gemini.go index 8e21cc6fd0..d08524f7bd 100644 --- a/setting/model_setting/gemini.go +++ b/setting/model_setting/gemini.go @@ -2,6 +2,7 @@ package model_setting import ( "fmt" + "slices" "github.com/QuantumNous/new-api/common" "github.com/QuantumNous/new-api/setting/config" @@ -108,10 +109,5 @@ func GetGeminiVersionSetting(key string) string { } func IsGeminiModelSupportImagine(model string) bool { - for _, v := range geminiSettings.SupportedImagineModels { - if v == model { - return true - } - } - return false + return slices.Contains(geminiSettings.SupportedImagineModels, model) } diff --git a/setting/model_setting/global.go b/setting/model_setting/global.go index 77127ff5bd..b46d6f35e4 100644 --- a/setting/model_setting/global.go +++ b/setting/model_setting/global.go @@ -119,8 +119,8 @@ func compiledThinkingBlacklist() ([]string, []*regexp.Regexp) { if entry == "" { continue } - if strings.HasPrefix(entry, thinkingBlacklistRegexPrefix) { - pattern := strings.TrimPrefix(entry, thinkingBlacklistRegexPrefix) + if after, ok := strings.CutPrefix(entry, thinkingBlacklistRegexPrefix); ok { + pattern := after if pattern == "" { common.SysError(fmt.Sprintf("invalid thinking_model_blacklist regex %q: pattern is empty", entry)) continue @@ -150,10 +150,8 @@ func ShouldPreserveThinkingSuffix(modelName string) bool { } exact, regexes := compiledThinkingBlacklist() - for _, entry := range exact { - if entry == target { - return true - } + if slices.Contains(exact, target) { + return true } for _, re := range regexes { if re.MatchString(target) { diff --git a/setting/operation_setting/channel_affinity_setting.go b/setting/operation_setting/channel_affinity_setting.go index a925a847d6..79c5af3c2f 100644 --- a/setting/operation_setting/channel_affinity_setting.go +++ b/setting/operation_setting/channel_affinity_setting.go @@ -18,7 +18,7 @@ type ChannelAffinityRule struct { ValueRegex string `json:"value_regex"` TTLSeconds int `json:"ttl_seconds"` - ParamOverrideTemplate map[string]interface{} `json:"param_override_template,omitempty"` + ParamOverrideTemplate map[string]any `json:"param_override_template,omitempty"` SkipRetryOnFailure bool `json:"skip_retry_on_failure"` @@ -81,11 +81,11 @@ var claudeCliPassThroughHeaders = []string{ "Anthropic-Version", } -func buildPassHeaderTemplate(headers []string) map[string]interface{} { +func buildPassHeaderTemplate(headers []string) map[string]any { clonedHeaders := make([]string, 0, len(headers)) clonedHeaders = append(clonedHeaders, headers...) - return map[string]interface{}{ - "operations": []map[string]interface{}{ + return map[string]any{ + "operations": []map[string]any{ { "mode": "pass_headers", "value": clonedHeaders, @@ -95,11 +95,11 @@ func buildPassHeaderTemplate(headers []string) map[string]interface{} { } } -func buildCodexPassHeaderTemplate() map[string]interface{} { +func buildCodexPassHeaderTemplate() map[string]any { requestHeaders := make([]string, 0, len(codexCliPassThroughHeaders)) requestHeaders = append(requestHeaders, codexCliPassThroughHeaders...) - return map[string]interface{}{ - "operations": []map[string]interface{}{ + return map[string]any{ + "operations": []map[string]any{ { "mode": "pass_headers", "value": requestHeaders, diff --git a/setting/operation_setting/operation_setting.go b/setting/operation_setting/operation_setting.go index ef330d1adb..1abfaf086b 100644 --- a/setting/operation_setting/operation_setting.go +++ b/setting/operation_setting/operation_setting.go @@ -21,8 +21,8 @@ func AutomaticDisableKeywordsToString() string { func AutomaticDisableKeywordsFromString(s string) { AutomaticDisableKeywords = []string{} - ak := strings.Split(s, "\n") - for _, k := range ak { + ak := strings.SplitSeq(s, "\n") + for k := range ak { k = strings.TrimSpace(k) k = strings.ToLower(k) if k != "" { diff --git a/setting/operation_setting/tools.go b/setting/operation_setting/tools.go index 07560f89e9..da05a74fe5 100644 --- a/setting/operation_setting/tools.go +++ b/setting/operation_setting/tools.go @@ -162,13 +162,13 @@ func RebuildToolPriceIndex() { } for key, price := range merged { - colonIdx := strings.IndexByte(key, ':') - if colonIdx < 0 { + before, after, ok := strings.Cut(key, ":") + if !ok { idx.defaults[key] = price continue } - toolName := key[:colonIdx] - modelPart := key[colonIdx+1:] + toolName := before + modelPart := after prefix := strings.TrimSuffix(modelPart, "*") idx.prefixes[toolName] = append(idx.prefixes[toolName], prefixEntry{prefix: prefix, price: price}) } diff --git a/setting/operation_setting/tools_price_test.go b/setting/operation_setting/tools_price_test.go index 027b51929c..915c377c0c 100644 --- a/setting/operation_setting/tools_price_test.go +++ b/setting/operation_setting/tools_price_test.go @@ -1,6 +1,7 @@ package operation_setting import ( + "maps" "math" "testing" @@ -11,9 +12,7 @@ import ( func preserveToolPrices(t *testing.T) { t.Helper() original := make(map[string]float64, len(toolPriceSetting.Prices)) - for key, price := range toolPriceSetting.Prices { - original[key] = price - } + maps.Copy(original, toolPriceSetting.Prices) t.Cleanup(func() { toolPriceSetting.Prices = original RebuildToolPriceIndex() diff --git a/setting/ratio_setting/exposed_cache.go b/setting/ratio_setting/exposed_cache.go index c88216fcb0..61c400e3d2 100644 --- a/setting/ratio_setting/exposed_cache.go +++ b/setting/ratio_setting/exposed_cache.go @@ -1,6 +1,7 @@ package ratio_setting import ( + "maps" "sync" "sync/atomic" "time" @@ -26,9 +27,7 @@ func InvalidateExposedDataCache() { func cloneGinH(src gin.H) gin.H { dst := make(gin.H, len(src)) - for k, v := range src { - dst[k] = v - } + maps.Copy(dst, src) return dst } diff --git a/setting/ratio_setting/model_ratio.go b/setting/ratio_setting/model_ratio.go index b1e0b364d6..4d1846c79a 100644 --- a/setting/ratio_setting/model_ratio.go +++ b/setting/ratio_setting/model_ratio.go @@ -1,6 +1,7 @@ package ratio_setting import ( + "maps" "strings" "github.com/QuantumNous/new-api/common" @@ -419,9 +420,7 @@ func GetDefaultPricingMaps() map[string]map[string]float64 { result := make(map[string]map[string]float64, len(defaults)) for key, values := range defaults { result[key] = make(map[string]float64, len(values)) - for name, value := range values { - result[key][name] = value - } + maps.Copy(result[key], values) } return result } diff --git a/setting/sensitive.go b/setting/sensitive.go index 86f9be9a6e..5ef0c1c771 100644 --- a/setting/sensitive.go +++ b/setting/sensitive.go @@ -25,8 +25,8 @@ func SensitiveWordsToString() string { func SensitiveWordsFromString(s string) { SensitiveWords = []string{} - sw := strings.Split(s, "\n") - for _, w := range sw { + sw := strings.SplitSeq(s, "\n") + for w := range sw { w = strings.TrimSpace(w) if w != "" { SensitiveWords = append(SensitiveWords, w) diff --git a/setting/system_setting/task_artifact_store.go b/setting/system_setting/task_artifact_store.go index 8bdfe393b4..bc883bb3ee 100644 --- a/setting/system_setting/task_artifact_store.go +++ b/setting/system_setting/task_artifact_store.go @@ -132,7 +132,7 @@ func ValidateTaskArtifactStoreConfig(config TaskArtifactStoreConfig) error { strings.HasPrefix(config.S3Prefix, "/") || strings.Contains(config.S3Prefix, "\\") { return errors.New("S3 prefix syntax is invalid") } - for _, part := range strings.Split(config.S3Prefix, "/") { + for part := range strings.SplitSeq(config.S3Prefix, "/") { if part == "." || part == ".." { return errors.New("S3 prefix must not contain dot segments") } diff --git a/setting/task_plugin.go b/setting/task_plugin.go index 04731017f9..32c35feead 100644 --- a/setting/task_plugin.go +++ b/setting/task_plugin.go @@ -1,6 +1,7 @@ package setting import ( + "slices" "sort" "strings" @@ -111,10 +112,5 @@ func SetTaskPluginDisabledFactoryKeysOption(keys []string) error { } func IsTaskPluginFactoryDisabled(key string) bool { - for _, item := range GetTaskPluginDisabledFactoryKeys() { - if item == key { - return true - } - } - return false + return slices.Contains(GetTaskPluginDisabledFactoryKeys(), key) } diff --git a/setting/user_usable_group.go b/setting/user_usable_group.go index eb04b7f305..39c692ce68 100644 --- a/setting/user_usable_group.go +++ b/setting/user_usable_group.go @@ -2,6 +2,7 @@ package setting import ( "encoding/json" + "maps" "sync" "github.com/QuantumNous/new-api/common" @@ -18,9 +19,7 @@ func GetUserUsableGroupsCopy() map[string]string { defer userUsableGroupsMutex.RUnlock() copyUserUsableGroups := make(map[string]string) - for k, v := range userUsableGroups { - copyUserUsableGroups[k] = v - } + maps.Copy(copyUserUsableGroups, userUsableGroups) return copyUserUsableGroups }