{"modulePath":"github.com/MAX-API-Next/MAX-API","version":"v1.0.5","isLatest":true,"isStandardLibrary":false,"goos":"linux","goarch":"amd64","docs":"# package common\n\n## Constants\n\n```go\nconst (\n\tNodeNameSourceManual   = \"manual\"\n\tNodeNameSourceHostname = \"hostname\"\n)\n```\n\n```go\nconst (\n\tRequestIdKey         = \"X-Oneapi-Request-Id\"\n\tUpstreamRequestIdKey = \"X-Upstream-Request-Id\"\n)\n```\n\n```go\nconst (\n\tRoleGuestUser  = 0\n\tRoleCommonUser = 1\n\tRoleAdminUser  = 10\n\tRoleRootUser   = 100\n)\n```\n\n```go\nconst (\n\tUserStatusEnabled  = 1 // don't use 0, 0 is the default value!\n\tUserStatusDisabled = 2 // also don't use 0\n)\n```\n\n```go\nconst (\n\tTokenStatusEnabled   = 1 // don't use 0, 0 is the default value!\n\tTokenStatusDisabled  = 2 // also don't use 0\n\tTokenStatusExpired   = 3\n\tTokenStatusExhausted = 4\n)\n```\n\n```go\nconst (\n\tRedemptionCodeStatusEnabled  = 1 // don't use 0, 0 is the default value!\n\tRedemptionCodeStatusDisabled = 2 // also don't use 0\n\tRedemptionCodeStatusUsed     = 3 // also don't use 0\n)\n```\n\n```go\nconst (\n\tChannelStatusUnknown          = 0\n\tChannelStatusEnabled          = 1 // don't use 0, 0 is the default value!\n\tChannelStatusManuallyDisabled = 2 // also don't use 0\n\tChannelStatusAutoDisabled     = 3\n)\n```\n\n```go\nconst (\n\tTopUpStatusPending = \"pending\"\n\tTopUpStatusSuccess = \"success\"\n\tTopUpStatusFailed  = \"failed\"\n\tTopUpStatusExpired = \"expired\"\n)\n```\n\n```go\nconst (\n\tDatabaseTypeMySQL      = \"mysql\"\n\tDatabaseTypeSQLite     = \"sqlite\"\n\tDatabaseTypePostgreSQL = \"postgres\"\n)\n```\n\n```go\nconst (\n\tMaxQuota = math.MaxInt32\n\tMinQuota = math.MinInt32\n)\n```\nQuota conversions are centralized here so every billing path shares one saturation + logging policy. Quota columns are 32-bit integers in supported deployments, so an oversized product must clamp to the int32 range instead of wrapping around and turning a charge into a credit.\n\n```go\nconst (\n\t// 备用码配置\n\tBackupCodeLength = 8 // 备用码长度\n\tBackupCodeCount  = 4 // 生成备用码数量\n\n\t// 限制配置\n\tMaxFailAttempts = 5   // 最大失败尝试次数\n\tLockoutDuration = 300 // 锁定时间（秒）\n)\n```\n\n```go\nconst (\n\tEmailVerificationPurpose = \"v\"\n\tPasswordResetPurpose     = \"r\"\n)\n```\n\n```go\nconst DefaultLogo = \"/max-api-logo.png\"\n```\n\n```go\nconst KeyBodyStorage = \"key_body_storage\"\n```\n\n```go\nconst KeyRequestBody = \"key_request_body\"\n```\n\n```go\nconst LegacyDefaultLogo = \"/logo.png\"\n```\n\n```go\nconst LocalLogContentLimit = 2048\n```\n\n```go\nconst PersistedLogContentLimit = 4096\n```\n\n## Variables\n\n```go\nvar (\n\tFileUploadPermission    = RoleGuestUser\n\tFileDownloadPermission  = RoleGuestUser\n\tImageUploadPermission   = RoleGuestUser\n\tImageDownloadPermission = RoleGuestUser\n)\n```\n\n```go\nvar (\n\tGlobalApiRateLimitEnable   bool\n\tGlobalApiRateLimitNum      int\n\tGlobalApiRateLimitDuration int64\n\n\tGlobalWebRateLimitEnable   bool\n\tGlobalWebRateLimitNum      int\n\tGlobalWebRateLimitDuration int64\n\n\tCriticalRateLimitEnable        bool\n\tCriticalRateLimitNum                 = 20\n\tCriticalRateLimitDuration      int64 = 20 * 60\n\tCriticalRouteRateLimitNum            = 20\n\tCriticalRouteRateLimitDuration int64 = 20 * 60\n\n\t// Password login is limited by account as well as the shared API bucket.\n\t// This prevents a shared NAT address from making unrelated users unable to log in.\n\tLoginRateLimitEnable   bool\n\tLoginRateLimitNum            = 10\n\tLoginRateLimitDuration int64 = 15 * 60\n\n\tUploadRateLimitNum            = 10\n\tUploadRateLimitDuration int64 = 60\n\n\tDownloadRateLimitNum            = 10\n\tDownloadRateLimitDuration int64 = 60\n\n\t// Per-user search rate limit (applies after authentication, keyed by user ID)\n\tSearchRateLimitEnable         = true\n\tSearchRateLimitNum            = 10\n\tSearchRateLimitDuration int64 = 60\n)\n```\nAll duration's unit is seconds Shouldn't larger then RateLimitKeyExpirationDuration\n\n```go\nvar (\n\tPort         = flag.Int(\"port\", 3000, \"the listening port\")\n\tPrintVersion = flag.Bool(\"version\", false, \"print version and exit\")\n\tPrintHelp    = flag.Bool(\"help\", false, \"print help and exit\")\n\tLogDir       = flag.String(\"log-dir\", \"./logs\", \"specify the log directory\")\n)\n```\n\n```go\nvar (\n\t// OpenAIResponseOnlyModels is a list of models that are only available for OpenAI responses.\n\tOpenAIResponseOnlyModels = []string{\n\t\t\"o3-pro\",\n\t\t\"o3-deep-research\",\n\t\t\"o4-mini-deep-research\",\n\t}\n\tImageGenerationModels = []string{\n\t\t\"dall-e-3\",\n\t\t\"dall-e-2\",\n\t\t\"gpt-image-1\",\n\t\t\"prefix:imagen-\",\n\t\t\"flux-\",\n\t\t\"flux.1-\",\n\t}\n\tOpenAITextModels = []string{\n\t\t\"gpt-\",\n\t\t\"o1\",\n\t\t\"o3\",\n\t\t\"o4\",\n\t\t\"chatgpt\",\n\t}\n)\n```\n\n```go\nvar AutomaticDisableChannelEnabled = false\n```\n\n```go\nvar AutomaticEnableChannelEnabled = false\n```\n\n```go\nvar BatchUpdateEnabled = false\n```\n\n```go\nvar BatchUpdateInterval int\n```\n\n```go\nvar ChannelDisableThreshold = 5.0\n```\n\n```go\nvar CohereSafetySetting string\n```\n[https://docs.cohere.com/docs/safety-modes](https://docs.cohere.com/docs/safety-modes) Type; NONE/CONTEXTUAL/STRICT\n\n```go\nvar CryptoSecret = uuid.New().String()\n```\n\n```go\nvar DataExportDefaultTime = \"hour\" // unit: minute\n\n```\n\n```go\nvar DataExportEnabled = true\n```\n\n```go\nvar DataExportInterval = 5 // unit: minute\n\n```\n\n```go\nvar DebugEnabled bool\n```\n\n```go\nvar DefaultCollapseSidebar = false // default value of collapse sidebar\n\n```\n\n```go\nvar DefaultSSRFProtection = \u0026SSRFProtection{\n\tAllowPrivateIp:   false,\n\tDomainFilterMode: true,\n\tDomainList:       []string{},\n\tIpFilterMode:     true,\n\tIpList:           []string{},\n\tAllowedPorts:     []int{},\n}\n```\nDefaultSSRFProtection 默认SSRF防护配置\n\n```go\nvar DefaultTrustedProxies = []string{\n\t\"127.0.0.0/8\",\n\t\"::1/128\",\n}\n```\n\n```go\nvar DisplayInCurrencyEnabled = true\n```\n保留旧变量以兼容历史逻辑，实际展示由 general\\_setting.quota\\_display\\_type 控制\n\n```go\nvar DisplayTokenStatEnabled = true\n```\n\n```go\nvar DrawingEnabled = true\n```\n\n```go\nvar EmailAliasRestrictionEnabled = false // 是否启用邮箱别名限制\n\n```\n\n```go\nvar EmailDomainRestrictionEnabled = false // 是否启用邮箱域名限制\n\n```\n\n```go\nvar EmailDomainWhitelist = []string{\n\t\"gmail.com\",\n\t\"163.com\",\n\t\"126.com\",\n\t\"qq.com\",\n\t\"outlook.com\",\n\t\"hotmail.com\",\n\t\"icloud.com\",\n\t\"yahoo.com\",\n\t\"foxmail.com\",\n}\n```\n\n```go\nvar EmailLoginAuthServerList = []string{\n\t\"smtp.sendcloud.net\",\n\t\"smtp.azurecomm.net\",\n}\n```\n\n```go\nvar EmailVerificationEnabled = false\n```\n\n```go\nvar EmptyCompletionRetryEnabled = false\n```\n\n```go\nvar ErrRequestBodyTooLarge = errors.New(\"request body too large\")\n```\n\n```go\nvar ErrSMTPStartTLSUnsupported = errors.New(\"smtp server does not support STARTTLS\")\n```\n\n```go\nvar ErrStorageClosed = fmt.Errorf(\"body storage is closed\")\n```\nErrStorageClosed 存储已关闭错误\n\n```go\nvar Footer = \"\"\n```\n\n```go\nvar GeminiSafetySetting string\n```\n\n```go\nvar GitHubClientId = \"\"\n```\n\n```go\nvar GitHubClientSecret = \"\"\n```\n\n```go\nvar GitHubOAuthEnabled = false\n```\n\n```go\nvar InsecureTLSConfig = \u0026tls.Config{InsecureSkipVerify: true}\n```\n\n```go\nvar IsMasterNode bool\n```\n\n```go\nvar ItemsPerPage = 10\n```\n\n```go\nvar LinuxDOClientId = \"\"\n```\n\n```go\nvar LinuxDOClientSecret = \"\"\n```\n\n```go\nvar LinuxDOMinimumTrustLevel = 0\n```\n\n```go\nvar LinuxDOOAuthEnabled = false\n```\n\n```go\nvar LogConsumeEnabled = true\n```\n\n```go\nvar LogContentMaxCharacters = 12000\n```\n\n```go\nvar LogRequestContentEnabled = false\n```\n\n```go\nvar LogResponseContentEnabled = false\n```\n\n```go\nvar LogSqlType = DatabaseTypeSQLite // Default to SQLite for logging SQL queries\n\n```\n\n```go\nvar LogWriterMu sync.RWMutex\n```\nLogWriterMu protects concurrent access to gin.DefaultWriter/gin.DefaultErrorWriter during log file rotation. Acquire RLock when reading/writing through the writers, acquire Lock when swapping writers and closing old files.\n\n```go\nvar Logo = \"\"\n```\n\n```go\nvar MaxRecentItems = 1000\n```\n\n```go\nvar MemoryCacheEnabled bool\n```\n\n```go\nvar NodeName = \"\"\n```\nNodeName 节点名称，从 NODE\\_NAME 环境变量读取； 用于审计日志中标识节点身份，在容器/K8s 部署时比自动探测到的容器内网 IP 更具可读性。\n\n```go\nvar NodeNameManuallyConfigured bool\n```\n\n```go\nvar NodeNameSource = NodeNameSourceHostname\n```\n\n```go\nvar OptionMap map[string]string\n```\n\n```go\nvar OptionMapRWMutex sync.RWMutex\n```\n\n```go\nvar PasswordLoginEnabled = true\n```\n\n```go\nvar PasswordRegisterEnabled = true\n```\n\n```go\nvar PreConsumedQuota = 500\n```\n\n```go\nvar QuotaForInvitee = 0\n```\n\n```go\nvar QuotaForInviter = 0\n```\n\n```go\nvar QuotaForNewUser = 0\n```\n\n```go\nvar QuotaPerUnit = 500 * 1000.0 // $0.002 / 1K tokens\n\n```\nvar ChatLink = \"\" var ChatLink2 = \"\"\n\n```go\nvar QuotaRemindThreshold = 1000\n```\n\n```go\nvar RDB *redis.Client\n```\n\n```go\nvar RateLimitKeyExpirationDuration = 20 * time.Minute\n```\n\n```go\nvar RedisEnabled = true\n```\n\n```go\nvar RegisterEnabled = true\n```\n\n```go\nvar RelayIdleConnTimeout int // unit is second\n\n```\n\n```go\nvar RelayMaxIdleConns int\n```\n\n```go\nvar RelayMaxIdleConnsPerHost int\n```\n\n```go\nvar RelayTimeout int // unit is second\n\n```\n\n```go\nvar RequestInterval time.Duration\n```\n\n```go\nvar RetryTimes = 0\n```\n\n```go\nvar SMTPAccount = \"\"\n```\n\n```go\nvar SMTPForceAuthLogin = false\n```\n\n```go\nvar SMTPFrom = \"\"\n```\n\n```go\nvar SMTPInsecureSkipVerify = false\n```\n\n```go\nvar SMTPPort = 587\n```\n\n```go\nvar SMTPSSLEnabled = false\n```\n\n```go\nvar SMTPServer = \"\"\n```\n\n```go\nvar SMTPStartTLSEnabled = false\n```\n\n```go\nvar SMTPToken = \"\"\n```\n\n```go\nvar SQLitePath = \"one-api.db?_busy_timeout=30000\"\n```\n\n```go\nvar SessionCookieSecure = false\n```\n\n```go\nvar SessionSecret = uuid.New().String()\n```\n\n```go\nvar StartTime = time.Now().Unix() // unit: second\n\n```\n\n```go\nvar SyncFrequency int // unit is second\n\n```\n\n```go\nvar SystemName = \"MAX API\"\n```\n\n```go\nvar TLSInsecureSkipVerify bool\n```\n\n```go\nvar TaskEnabled = true\n```\n\n```go\nvar TelegramBotName = \"\"\n```\n\n```go\nvar TelegramBotToken = \"\"\n```\n\n```go\nvar TelegramOAuthEnabled = false\n```\n\n```go\nvar TopUpLink = \"\"\n```\n\n```go\nvar TranslateMessage func(c *gin.Context, key string, args ...map[string]any) string\n```\nTranslateMessage is a helper function that calls i18n.T This function is defined here to avoid circular imports The actual implementation will be set during init\n\n```go\nvar TrustedProxies []string\n```\n\n```go\nvar TurnstileCheckEnabled = false\n```\n\n```go\nvar TurnstileSecretKey = \"\"\n```\n\n```go\nvar TurnstileSiteKey = \"\"\n```\n\n```go\nvar UsingClickHouse = false\n```\n\n```go\nvar UsingMySQL = false\n```\n\n```go\nvar UsingPostgreSQL = false\n```\n\n```go\nvar UsingSQLite = false\n```\n\n```go\nvar Validate *validator.Validate\n```\n\n```go\nvar VerificationValidMinutes = 10\n```\n\n```go\nvar Version = \"v0.0.0\" // this hard coding will be replaced automatically when building, no need to manually change\n\n```\n\n```go\nvar WeChatAccountQRCodeImageURL = \"\"\n```\n\n```go\nvar WeChatAuthEnabled = false\n```\n\n```go\nvar WeChatServerAddress = \"\"\n```\n\n```go\nvar WeChatServerToken = \"\"\n```\n\n## Functions\n\n```go\nfunc Any2Type[T any](data any) (T, error)\n```\n\n```go\nfunc ApiError(c *gin.Context, err error)\n```\n\n```go\nfunc ApiErrorI18n(c *gin.Context, key string, args ...map[string]any)\n```\nApiErrorI18n returns a translated error message based on the user's language preference key is the i18n message key, args is optional template data\n\n```go\nfunc ApiErrorMsg(c *gin.Context, msg string)\n```\n\n```go\nfunc ApiSuccess(c *gin.Context, data any)\n```\n\n```go\nfunc ApiSuccessI18n(c *gin.Context, key string, data any, args ...map[string]any)\n```\nApiSuccessI18n returns a translated success message based on the user's language preference\n\n```go\nfunc AutoSMTPAuth(username, password string) smtp.Auth\n```\n\n```go\nfunc BuildURL(base string, endpoint string) string\n```\nBuildURL concatenates base and endpoint, returns the complete url string\n\n```go\nfunc Bytes2Size(num int64) string\n```\n\n```go\nfunc ChannelType2APIType(channelType int) (int, bool)\n```\n\n```go\nfunc CleanupBodyStorage(c *gin.Context)\n```\nCleanupBodyStorage 清理请求体存储（应在请求结束时调用）\n\n```go\nfunc CleanupOldCacheFiles()\n```\nCleanupOldCacheFiles 清理旧的缓存文件（用于启动时清理残留）\n\n```go\nfunc CleanupOldDiskCacheFiles(maxAge time.Duration) error\n```\nCleanupOldDiskCacheFiles 清理旧的缓存文件 maxAge: 文件最大存活时间 注意：此函数只删除文件，不更新统计（因为无法知道每个文件的原始大小）\n\n```go\nfunc CreateDiskCacheFile(cacheType DiskCacheType) (string, *os.File, error)\n```\nCreateDiskCacheFile 创建磁盘缓存文件 cacheType: 缓存类型（body/file） 返回文件路径和文件句柄\n\n```go\nfunc DecodeJson(reader io.Reader, v any) error\n```\n\n```go\nfunc DecrementDiskFiles(size int64)\n```\nDecrementDiskFiles 减少磁盘文件计数\n\n```go\nfunc DecrementMemoryBuffers(size int64)\n```\nDecrementMemoryBuffers 减少内存缓存计数\n\n```go\nfunc DeepCopy[T any](src *T) (*T, error)\n```\n\n```go\nfunc DeleteKey(key string, purpose string)\n```\n\n```go\nfunc EmbedFolder(fsEmbed embed.FS, targetPath string) static.ServeFileSystem\n```\n\n```go\nfunc EncodeBase64(str string) string\n```\n\n```go\nfunc EnsureDiskCacheDir() error\n```\nEnsureDiskCacheDir 确保缓存目录存在\n\n```go\nfunc FatalLog(v ...any)\n```\n\n```go\nfunc GenerateBackupCodes() ([]string, error)\n```\nGenerateBackupCodes 生成备用恢复码\n\n```go\nfunc GenerateHMAC(data string) string\n```\n\n```go\nfunc GenerateHMACWithKey(key []byte, data string) string\n```\n\n```go\nfunc GenerateKey() (string, error)\n```\n\n```go\nfunc GenerateQRCodeData(secret, username string) string\n```\nGenerateQRCodeData 生成二维码数据\n\n```go\nfunc GenerateRandomCharsKey(length int) (string, error)\n```\n\n```go\nfunc GenerateRandomKey(length int) (string, error)\n```\n\n```go\nfunc GenerateTOTPSecret(accountName string) (*otp.Key, error)\n```\nGenerateTOTPSecret 生成TOTP密钥和配置\n\n```go\nfunc GenerateVerificationCode(length int) string\n```\n\n```go\nfunc Get2FAIssuer() string\n```\nGet2FAIssuer 获取2FA发行者名称\n\n```go\nfunc GetAnonymousRequestBodyLimitBytes() int64\n```\n\n```go\nfunc GetAudioDuration(ctx context.Context, f io.ReadSeeker, ext string) (duration float64, err error)\n```\nGetAudioDuration 使用纯 Go 库获取音频文件的时长（秒）。 它不再依赖外部的 ffmpeg 或 ffprobe 程序。\n\n```go\nfunc GetContextKey(c *gin.Context, key constant.ContextKey) (any, bool)\n```\n\n```go\nfunc GetContextKeyBool(c *gin.Context, key constant.ContextKey) bool\n```\n\n```go\nfunc GetContextKeyInt(c *gin.Context, key constant.ContextKey) int\n```\n\n```go\nfunc GetContextKeyInt64(c *gin.Context, key constant.ContextKey) int64\n```\n\n```go\nfunc GetContextKeyString(c *gin.Context, key constant.ContextKey) string\n```\n\n```go\nfunc GetContextKeyStringMap(c *gin.Context, key constant.ContextKey) map[string]any\n```\n\n```go\nfunc GetContextKeyStringSlice(c *gin.Context, key constant.ContextKey) []string\n```\n\n```go\nfunc GetContextKeyTime(c *gin.Context, key constant.ContextKey) time.Time\n```\n\n```go\nfunc GetContextKeyType[T any](c *gin.Context, key constant.ContextKey) (T, bool)\n```\n\n```go\nfunc GetDefaultEndpointTypeByPath(path string) (constant.EndpointType, bool)\n```\nGetDefaultEndpointTypeByPath returns the built-in endpoint type for an exact path.\n\n```go\nfunc GetDiskCacheDir() string\n```\nGetDiskCacheDir 获取统一的磁盘缓存目录 注意：每次调用都会重新计算，以响应配置变化\n\n```go\nfunc GetDiskCacheInfo() (fileCount int, totalSize int64, err error)\n```\nGetDiskCacheInfo 获取磁盘缓存目录信息\n\n```go\nfunc GetDiskCacheMaxSizeBytes() int64\n```\nGetDiskCacheMaxSizeBytes 获取磁盘缓存最大大小（字节）\n\n```go\nfunc GetDiskCachePath() string\n```\nGetDiskCachePath 获取磁盘缓存目录\n\n```go\nfunc GetDiskCacheThresholdBytes() int64\n```\nGetDiskCacheThresholdBytes 获取磁盘缓存阈值（字节）\n\n```go\nfunc GetEndpointTypesByChannelType(channelType int, modelName string) []constant.EndpointType\n```\nGetEndpointTypesByChannelType 获取渠道最优先端点类型（所有的渠道都支持 OpenAI 端点）\n\n```go\nfunc GetEnvOrDefault(env string, defaultValue int) int\n```\n\n```go\nfunc GetEnvOrDefaultBool(env string, defaultValue bool) bool\n```\n\n```go\nfunc GetEnvOrDefaultString(env string, defaultValue string) string\n```\n\n```go\nfunc GetIp() (ip string)\n```\n\n```go\nfunc GetJsonString(data any) string\n```\n\n```go\nfunc GetJsonType(data json.RawMessage) string\n```\n\n```go\nfunc GetNetworkIps() []string\n```\n\n```go\nfunc GetPointer[T any](v T) *T\n```\n\n```go\nfunc GetRandomInt(max int) int\n```\n\n```go\nfunc GetRandomString(length int) string\n```\n\n```go\nfunc GetRequestBody(c *gin.Context) (io.Seeker, error)\n```\n\n```go\nfunc GetStringIfEmpty(str string, defaultValue string) string\n```\n\n```go\nfunc GetTheme() string\n```\n\n```go\nfunc GetTimeString() string\n```\n\n```go\nfunc GetTimestamp() int64\n```\n\n```go\nfunc GetTopupGroupRatio(name string) float64\n```\n\n```go\nfunc GetTrustQuota() int\n```\n\n```go\nfunc GetUUID() string\n```\n\n```go\nfunc HashBackupCode(code string) (string, error)\n```\nHashBackupCode 对备用码进行哈希\n\n```go\nfunc HmacSha256(message, key string) string\n```\n\n```go\nfunc HmacSha256Raw(message, key []byte) []byte\n```\n\n```go\nfunc IncrementDiskCacheHits()\n```\nIncrementDiskCacheHits 增加磁盘缓存命中次数\n\n```go\nfunc IncrementDiskFiles(size int64)\n```\nIncrementDiskFiles 增加磁盘文件计数\n\n```go\nfunc IncrementMemoryBuffers(size int64)\n```\nIncrementMemoryBuffers 增加内存缓存计数\n\n```go\nfunc IncrementMemoryCacheHits()\n```\nIncrementMemoryCacheHits 增加内存缓存命中次数\n\n```go\nfunc InitEnv()\n```\n\n```go\nfunc InitRedisClient() (err error)\n```\nInitRedisClient This function is called after init()\n\n```go\nfunc IntMax(a int, b int) int\n```\n\n```go\nfunc Interface2String(inter interface{}) string\n```\n\n```go\nfunc IsDiskCacheAvailable(requestSize int64) bool\n```\nIsDiskCacheAvailable 检查是否可以创建新的磁盘缓存\n\n```go\nfunc IsDiskCacheEnabled() bool\n```\nIsDiskCacheEnabled 是否启用磁盘缓存\n\n```go\nfunc IsIP(s string) bool\n```\n\n```go\nfunc IsImageGenerationModel(modelName string) bool\n```\n\n```go\nfunc IsIpInCIDRList(ip net.IP, cidrList []string) bool\n```\n\n```go\nfunc IsJsonArray(str string) bool\n```\n\n```go\nfunc IsJsonObject(str string) bool\n```\n\n```go\nfunc IsOpenAIResponseOnlyModel(modelName string) bool\n```\n\n```go\nfunc IsOpenAITextModel(modelName string) bool\n```\n\n```go\nfunc IsPrivateIP(ip net.IP) bool\n```\n\n```go\nfunc IsRequestBodyTooLargeError(err error) bool\n```\n\n```go\nfunc IsRunningInContainer() bool\n```\nIsRunningInContainer detects if the application is running inside a container\n\n```go\nfunc IsValidateRole(role int) bool\n```\n\n```go\nfunc JsonRawMessageToString(data json.RawMessage) string\n```\nJsonRawMessageToString returns JSON strings as their decoded value and other JSON values as raw text.\n\n```go\nfunc LocalLogPreview(content string) string\n```\nLocalLogPreview limits log-only content unless debug logging is enabled.\n\n```go\nfunc LogStartupSuccess(startTime time.Time, port string)\n```\n\n```go\nfunc LoginAuth(username, password string) smtp.Auth\n```\n\n```go\nfunc MapToJsonStr(m map[string]interface{}) string\n```\n\n```go\nfunc Marshal(v any) ([]byte, error)\n```\n\n```go\nfunc MaskEmail(email string) string\n```\nMaskEmail masks a user email to prevent PII leakage in logs Returns \"\\*\\*\\*masked\\*\\*\\*\" if email is empty, otherwise shows only the domain part\n\n```go\nfunc MaskSensitiveInfo(str string) string\n```\nMaskSensitiveInfo masks sensitive information like URLs, IPs, and domain names in a string Example: [http://example.com](http://example.com) -\u003e http://\\*\\*\\*.com [https://api.test.org/v1/users/123?key=secret](https://api.test.org/v1/users/123?key=secret) -\u003e https://\\*\\*\\*.org/\\*\\*\\*/\\*\\*\\*/?key=\\*\\*\\* [https://sub.domain.co.uk/path/to/resource](https://sub.domain.co.uk/path/to/resource) -\u003e https://\\*\\*\\*.co.uk/\\*\\*\\*/\\*\\*\\* 192.168.1.1 -\u003e \\*\\*\\*.\\*\\*\\*.\\*\\*\\*.\\*\\*\\* openai.com -\u003e \\*\\*\\*.com www.openai.com -\u003e \\*\\*\\*.\\*\\*\\*.com api.openai.com -\u003e \\*\\*\\*.\\*\\*\\*.com\n\n```go\nfunc Max(a int, b int) int\n```\n\n```go\nfunc MessageWithRequestId(message string, id string) string\n```\n\n```go\nfunc Monitor()\n```\nMonitor 定时监控cpu使用率，超过阈值输出pprof文件\n\n```go\nfunc MonitorContext(ctx context.Context)\n```\n\n```go\nfunc NormalizeBackupCode(code string) string\n```\nNormalizeBackupCode 标准化备用码格式\n\n```go\nfunc NormalizeBillingPreference(pref string) string\n```\nNormalizeBillingPreference clamps the billing preference to valid values.\n\n```go\nfunc NormalizeLogo(logo string) string\n```\n\n```go\nfunc OpenBrowser(url string)\n```\n\n```go\nfunc ParseIP(s string) net.IP\n```\n\n```go\nfunc ParseMultipartFormReusable(c *gin.Context) (*multipart.Form, error)\n```\n\n```go\nfunc ParseRedisOption() *redis.Options\n```\n\n```go\nfunc Password2Hash(password string) (string, error)\n```\n\n```go\nfunc QuotaFromDecimal(d decimal.Decimal) int\n```\nQuotaFromDecimal rounds a computed quota decimal before conversion.\n\n```go\nfunc QuotaFromFloat(value float64) int\n```\nQuotaFromFloat converts a computed quota value to int, truncating toward zero, with int32 saturation.\n\n```go\nfunc QuotaFromFloatStrict(value float64) (int, error)\n```\nQuotaFromFloatStrict rejects unrepresentable billing estimates instead of silently saturating them.\n\n```go\nfunc QuotaRound(value float64) int\n```\nQuotaRound converts a float64 quota value to int using half-away-from-zero rounding, with the same saturation policy.\n\n```go\nfunc QuotaRoundStrict(value float64) (int, error)\n```\n\n```go\nfunc RandomSleep()\n```\n\n```go\nfunc ReadDiskCacheFile(filePath string) ([]byte, error)\n```\nReadDiskCacheFile 读取磁盘缓存文件\n\n```go\nfunc ReadDiskCacheFileString(filePath string) (string, error)\n```\nReadDiskCacheFileString 读取磁盘缓存文件为字符串\n\n```go\nfunc ReaderOnly(r io.Reader) io.Reader\n```\nReaderOnly hides io.Closer while preserving replay metadata for BodyStorage.\n\n```go\nfunc RedisDel(key string) error\n```\n\n```go\nfunc RedisDelKey(key string) error\n```\n\n```go\nfunc RedisDeleteVersionedHash(key, versionKey string) error\n```\nRedisDeleteVersionedHash removes an entity cache and its generation marker. This is reserved for permanent entity deletion. Cache refills treat a missing generation as a fence miss, so deleting the marker cannot re-admit a snapshot captured before the entity was removed.\n\n```go\nfunc RedisGet(key string) (string, error)\n```\n\n```go\nfunc RedisGetCacheVersion(key string) (int64, error)\n```\nRedisGetCacheVersion reads a version used to fence cache-aside refills. A missing key is initialized from one shared monotonic sequence so deleting an entity's version marker never reuses its prior generation.\n\n```go\nfunc RedisHGetObj(key string, obj interface{}) error\n```\n\n```go\nfunc RedisHIncrBy(key, field string, delta int64) error\n```\n\n```go\nfunc RedisHSetField(key, field string, value interface{}) error\n```\n\n```go\nfunc RedisHSetFieldIfVersion(key, versionKey string, expectedVersion int64, field string, value interface{}, expiration time.Duration) (bool, error)\n```\nRedisHSetFieldIfVersion is the field-level variant used by narrow cache refills that must not overwrite unrelated hash fields.\n\n```go\nfunc RedisHSetObj(key string, obj interface{}, expiration time.Duration) error\n```\n\n```go\nfunc RedisHSetObjIfVersion(key, versionKey string, expectedVersion int64, obj interface{}, expiration time.Duration) (bool, error)\n```\nRedisHSetObjIfVersion stores a DB snapshot only while its cache generation is unchanged. WATCH makes the comparison and write safe across processes.\n\n```go\nfunc RedisIncr(key string, delta int64) error\n```\nRedisIncr Add this function to handle atomic increments\n\n```go\nfunc RedisInvalidateVersionedHash(key, versionKey string) error\n```\nRedisInvalidateVersionedHash advances the shared generation and removes the cached hash atomically, preventing older DB snapshots from refilling it.\n\n```go\nfunc RedisKeyCacheSeconds() int\n```\n\n```go\nfunc RedisSet(key string, value string, expiration time.Duration) error\n```\n\n```go\nfunc RegisterVerificationCodeWithKey(key string, code string, purpose string)\n```\n\n```go\nfunc RelayCtxGo(ctx context.Context, f func())\n```\n\n```go\nfunc RemoveDiskCacheFile(filePath string) error\n```\nRemoveDiskCacheFile 删除磁盘缓存文件\n\n```go\nfunc ResetDiskCacheStats()\n```\nResetDiskCacheStats 重置命中统计信息（不重置当前使用量）\n\n```go\nfunc ResetDiskCacheUsage()\n```\nResetDiskCacheUsage 重置磁盘缓存使用量统计（用于清理缓存后）\n\n```go\nfunc SafeSendBool(ch chan bool, value bool) (closed bool)\n```\n\n```go\nfunc SafeSendString(ch chan string, value string) (closed bool)\n```\n\n```go\nfunc SafeSendStringTimeout(ch chan string, value string, timeout int) (sent bool)\n```\nSafeSendStringTimeout returns true only when the value is sent before the timeout. A timeout or a closed channel returns false.\n\n```go\nfunc SanitizePersistedLogContent(content string) string\n```\n\n```go\nfunc SaveTmpFile(filename string, data io.Reader) (string, error)\n```\nSaveTmpFile saves data to a temporary file. The filename would be apppended with a random string.\n\n```go\nfunc Seconds2Time(num int) (time string)\n```\n\n```go\nfunc SecureRandomInt(max int) (int, error)\n```\n\n```go\nfunc SendEmail(subject string, receiver string, content string) error\n```\n\n```go\nfunc SessionCookieSecureForServerAddress(serverAddress string) bool\n```\n\n```go\nfunc SetContextKey(c *gin.Context, key constant.ContextKey, value any)\n```\n\n```go\nfunc SetDiskCacheConfig(config DiskCacheConfig)\n```\nSetDiskCacheConfig 设置磁盘缓存配置\n\n```go\nfunc SetPerformanceMonitorConfig(config PerformanceMonitorConfig)\n```\nSetPerformanceMonitorConfig 设置性能监控配置\n\n```go\nfunc SetTheme(_ string)\n```\nSetTheme is kept for configuration compatibility. Only the default frontend is supported.\n\n```go\nfunc Sha1(data []byte) string\n```\n\n```go\nfunc Sha1Raw(data []byte) []byte\n```\n\n```go\nfunc Sha256Raw(data []byte) []byte\n```\n\n```go\nfunc ShouldUseDiskCache(dataSize int64) bool\n```\nShouldUseDiskCache 判断是否应该使用磁盘缓存\n\n```go\nfunc StartPyroScope() error\n```\n\n```go\nfunc StartSystemMonitor()\n```\nStartSystemMonitor 启动系统监控\n\n```go\nfunc StopSystemMonitor(ctx context.Context) error\n```\n\n```go\nfunc StrToJsonArray(str string) ([]interface{}, error)\n```\n\n```go\nfunc StrToMap(str string) (map[string]interface{}, error)\n```\n\n```go\nfunc String2Int(str string) int\n```\n\n```go\nfunc StringToByteSlice(s string) []byte\n```\nStringToByteSlice \\[]byte only read, panic on append\n\n```go\nfunc StringsContains(strs []string, str string) bool\n```\n\n```go\nfunc SyncDiskCacheStats()\n```\nSyncDiskCacheStats 从实际磁盘状态同步统计信息 用于修正统计与实际不符的情况\n\n```go\nfunc SysError(s string)\n```\n\n```go\nfunc SysLog(s string)\n```\n\n```go\nfunc ThemeAwarePath(suffix string) string\n```\nThemeAwarePath rewrites legacy /console/\\* paths to their default frontend equivalents.\n\n```go\nfunc TopupGroupRatio2JSONString() string\n```\n\n```go\nfunc UnescapeHTML(x string) interface{}\n```\n\n```go\nfunc Unmarshal(data []byte, v any) error\n```\n\n```go\nfunc UnmarshalBodyReusable(c *gin.Context, v any) error\n```\n\n```go\nfunc UnmarshalJsonStr(data string, v any) error\n```\n\n```go\nfunc UpdateTopupGroupRatioByJSONString(jsonStr string) error\n```\n\n```go\nfunc ValidJSON(data []byte) bool\n```\n\n```go\nfunc ValidateBackupCode(code string) bool\n```\nValidateBackupCode 验证备用码格式\n\n```go\nfunc ValidateNumericCode(code string) (string, error)\n```\nValidateNumericCode 验证数字验证码格式\n\n```go\nfunc ValidatePasswordAndHash(password string, hash string) bool\n```\n\n```go\nfunc ValidateRedirectURL(rawURL string) error\n```\nValidateRedirectURL validates that a redirect URL is safe to use. It checks that:\n\n  - The URL is properly formatted\n  - The scheme is either http or https\n  - The domain is in the trusted domains list (exact match or subdomain)\n\nReturns nil if the URL is valid and trusted, otherwise returns an error describing why the validation failed.\n\n```go\nfunc ValidateTOTPCode(secret, code string) bool\n```\nValidateTOTPCode 验证TOTP验证码\n\n```go\nfunc ValidateURLWithFetchSetting(urlStr string, enableSSRFProtection, allowPrivateIp bool, domainFilterMode bool, ipFilterMode bool, domainList, ipList, allowedPorts []string, applyIPFilterForDomain bool) error\n```\nValidateURLWithFetchSetting 使用FetchSetting配置验证URL\n\n```go\nfunc VerifyAndDeleteCodeWithKey(key string, code string, purpose string) bool\n```\n\n```go\nfunc VerifyCodeWithKey(key string, code string, purpose string) bool\n```\n\n```go\nfunc VerifyCodeWithKeyAndRun(key string, code string, purpose string, fn func() error) (verified bool, err error)\n```\nVerifyCodeWithKeyAndRun reserves a code while fn runs. A successful fn consumes the code; an error or panic releases the reservation for retry.\n\n```go\nfunc WriteDiskCacheFile(cacheType DiskCacheType, data []byte) (string, error)\n```\nWriteDiskCacheFile 写入数据到磁盘缓存文件 返回文件路径\n\n```go\nfunc WriteDiskCacheFileString(cacheType DiskCacheType, data string) (string, error)\n```\nWriteDiskCacheFileString 写入字符串到磁盘缓存文件\n\n## Types\n\n```go\ntype BodyStorage interface {\n\tio.ReadSeeker\n\tio.Closer\n\t// Bytes 获取全部内容\n\tBytes() ([]byte, error)\n\t// Size 获取数据大小\n\tSize() int64\n\t// IsDisk 是否是磁盘存储\n\tIsDisk() bool\n\t// NewReader returns an independent reader positioned at the start.\n\tNewReader() (io.ReadCloser, error)\n}\n```\nBodyStorage 请求体存储接口\n\n```go\nfunc CreateBodyStorage(data []byte) (BodyStorage, error)\n```\nCreateBodyStorage 根据数据大小创建合适的存储\n\n```go\nfunc CreateBodyStorageFromReader(reader io.Reader, contentLength int64, maxBytes int64) (BodyStorage, error)\n```\nCreateBodyStorageFromReader 从 Reader 创建存储（用于大请求的流式处理）\n\n```go\nfunc GetBodyStorage(c *gin.Context) (BodyStorage, error)\n```\nGetBodyStorage 获取请求体存储对象（用于需要多次读取的场景）\n\n```go\ntype CustomEvent struct {\n\tEvent string\n\tId    string\n\tRetry uint\n\tData  interface{}\n}\n```\n\n```go\nfunc (r CustomEvent) Render(w http.ResponseWriter) error\n```\n\n```go\nfunc (r CustomEvent) WriteContentType(w http.ResponseWriter)\n```\n\n```go\ntype DiskCacheConfig struct {\n\t// Enabled 是否启用磁盘缓存\n\tEnabled bool\n\t// ThresholdMB 触发磁盘缓存的请求体大小阈值（MB）\n\tThresholdMB int\n\t// MaxSizeMB 磁盘缓存最大总大小（MB）\n\tMaxSizeMB int\n\t// Path 磁盘缓存目录\n\tPath string\n}\n```\nDiskCacheConfig 磁盘缓存配置（由 performance\\_setting 包更新）\n\n```go\nfunc GetDiskCacheConfig() DiskCacheConfig\n```\nGetDiskCacheConfig 获取磁盘缓存配置\n\n```go\ntype DiskCacheStats struct {\n\t// 当前活跃的磁盘缓存文件数\n\tActiveDiskFiles int64 `json:\"active_disk_files\"`\n\t// 当前磁盘缓存总大小（字节）\n\tCurrentDiskUsageBytes int64 `json:\"current_disk_usage_bytes\"`\n\t// 当前内存缓存数量\n\tActiveMemoryBuffers int64 `json:\"active_memory_buffers\"`\n\t// 当前内存缓存总大小（字节）\n\tCurrentMemoryUsageBytes int64 `json:\"current_memory_usage_bytes\"`\n\t// 磁盘缓存命中次数\n\tDiskCacheHits int64 `json:\"disk_cache_hits\"`\n\t// 内存缓存命中次数\n\tMemoryCacheHits int64 `json:\"memory_cache_hits\"`\n\t// 磁盘缓存最大限制（字节）\n\tDiskCacheMaxBytes int64 `json:\"disk_cache_max_bytes\"`\n\t// 磁盘缓存阈值（字节）\n\tDiskCacheThresholdBytes int64 `json:\"disk_cache_threshold_bytes\"`\n}\n```\nDiskCacheStats 磁盘缓存统计信息\n\n```go\nfunc GetDiskCacheStats() DiskCacheStats\n```\nGetDiskCacheStats 获取缓存统计信息\n\n```go\ntype DiskCacheType string\n```\nDiskCacheType 磁盘缓存类型\n\n```go\nconst (\n\tDiskCacheTypeBody DiskCacheType = \"body\" // 请求体缓存\n\tDiskCacheTypeFile DiskCacheType = \"file\" // 文件数据缓存\n)\n```\n\n```go\ntype DiskSpaceInfo struct {\n\t// 总空间（字节）\n\tTotal uint64 `json:\"total\"`\n\t// 可用空间（字节）\n\tFree uint64 `json:\"free\"`\n\t// 已用空间（字节）\n\tUsed uint64 `json:\"used\"`\n\t// 使用百分比\n\tUsedPercent float64 `json:\"used_percent\"`\n}\n```\nDiskSpaceInfo 磁盘空间信息\n\n```go\nfunc GetDiskSpaceInfo() DiskSpaceInfo\n```\nGetDiskSpaceInfo 获取缓存目录所在磁盘的空间信息 (Unix/Linux/macOS)\n\n```go\ntype EndpointInfo struct {\n\tPath   string `json:\"path\"`\n\tMethod string `json:\"method\"`\n}\n```\n\n```go\nfunc GetDefaultEndpointInfo(et constant.EndpointType) (EndpointInfo, bool)\n```\nGetDefaultEndpointInfo 返回指定端点类型的默认信息以及是否存在\n\n```go\ntype InMemoryRateLimiter struct {\n\t// contains filtered or unexported fields\n}\n```\n\n```go\nfunc (l *InMemoryRateLimiter) Allow(key string, maxRequestNum int, duration int64) bool\n```\n\n```go\nfunc (l *InMemoryRateLimiter) Init(expirationDuration time.Duration)\n```\n\n```go\nfunc (l *InMemoryRateLimiter) Request(key string, maxRequestNum int, duration int64) bool\n```\nRequest parameter duration's unit is seconds\n\n```go\nfunc (l *InMemoryRateLimiter) RequestWithRetry(key string, maxRequestNum int, duration int64) (bool, time.Duration)\n```\nRequestWithRetry records a request and returns the approximate time until the oldest request leaves the window when the request is rejected.\n\n```go\nfunc (l *InMemoryRateLimiter) Stop(ctx context.Context) error\n```\n\n```go\ntype NodeIdentity struct {\n\tName                    string `json:\"name\"`\n\tSource                  string `json:\"source\"`\n\tManuallyConfigured      bool   `json:\"manually_configured\"`\n\tShouldConfigureManually bool   `json:\"should_configure_manually\"`\n}\n```\n\n```go\nfunc GetNodeIdentity() NodeIdentity\n```\n\n```go\ntype PageInfo struct {\n\tPage     int `json:\"page\"`      // page num 页码\n\tPageSize int `json:\"page_size\"` // page size 页大小\n\n\tTotal int `json:\"total\"` // 总条数，后设置\n\tItems any `json:\"items\"` // 数据，后设置\n}\n```\n\n```go\nfunc GetPageQuery(c *gin.Context) *PageInfo\n```\n\n```go\nfunc (p *PageInfo) GetEndIdx() int\n```\n\n```go\nfunc (p *PageInfo) GetPage() int\n```\n\n```go\nfunc (p *PageInfo) GetPageSize() int\n```\n\n```go\nfunc (p *PageInfo) GetStartIdx() int\n```\n\n```go\nfunc (p *PageInfo) SetItems(items any)\n```\n\n```go\nfunc (p *PageInfo) SetTotal(total int)\n```\n\n```go\ntype PerformanceMonitorConfig struct {\n\tEnabled         bool\n\tCPUThreshold    int\n\tMemoryThreshold int\n\tDiskThreshold   int\n}\n```\nPerformanceMonitorConfig 性能监控配置\n\n```go\nfunc GetPerformanceMonitorConfig() PerformanceMonitorConfig\n```\nGetPerformanceMonitorConfig 获取性能监控配置\n\n```go\ntype QuotaClamp struct {\n\tOp       string         `json:\"op\"`\n\tKind     QuotaClampKind `json:\"kind\"`\n\tOriginal float64        `json:\"original\"`\n\tClamped  int            `json:\"clamped\"`\n}\n```\nQuotaClamp describes a single saturation event and is stored under admin\\_info.quota\\_saturation for audit when a billing path has to clamp.\n\n```go\nfunc QuotaFromDecimalChecked(d decimal.Decimal) (int, *QuotaClamp)\n```\n\n```go\nfunc QuotaFromFloatChecked(value float64) (int, *QuotaClamp)\n```\nQuotaFromFloatChecked is QuotaFromFloat plus a non-nil clamp descriptor when saturation or NaN fallback happened.\n\n```go\nfunc QuotaRoundChecked(value float64) (int, *QuotaClamp)\n```\n\n```go\nfunc (c *QuotaClamp) AuditMap() map[string]interface{}\n```\n\n```go\nfunc (c *QuotaClamp) Error() string\n```\n\n```go\ntype QuotaClampKind string\n```\nQuotaClampKind identifies why a quota conversion had to be saturated.\n\n```go\nconst (\n\tQuotaClampOverflow  QuotaClampKind = \"overflow\"\n\tQuotaClampUnderflow QuotaClampKind = \"underflow\"\n\tQuotaClampNaN       QuotaClampKind = \"nan\"\n)\n```\n\n```go\ntype ReplayableBody interface {\n\tio.Reader\n\tSize() int64\n\tNewReader() (io.ReadCloser, error)\n}\n```\nReplayableBody exposes body metadata without transferring storage ownership.\n\n```go\nfunc NewReplayableBodyReader(storage BodyStorage) ReplayableBody\n```\n\n```go\ntype SSRFProtection struct {\n\tAllowPrivateIp         bool\n\tDomainFilterMode       bool     // true: 白名单, false: 黑名单\n\tDomainList             []string // domain format, e.g. example.com, *.example.com\n\tIpFilterMode           bool     // true: 白名单, false: 黑名单\n\tIpList                 []string // CIDR or single IP\n\tAllowedPorts           []int    // 允许的端口范围\n\tApplyIPFilterForDomain bool     // 对域名启用IP过滤\n}\n```\nSSRFProtection SSRF防护配置\n\n```go\nfunc NewSSRFProtectionFromFetchSetting(allowPrivateIp bool, domainFilterMode bool, ipFilterMode bool, domainList, ipList, allowedPorts []string, applyIPFilterForDomain bool) (*SSRFProtection, error)\n```\n\n```go\nfunc NewSSRFProtectionWithFetchSetting(enableSSRFProtection, allowPrivateIp bool, domainFilterMode bool, ipFilterMode bool, domainList, ipList, allowedPorts []string, applyIPFilterForDomain bool) (*SSRFProtection, bool, error)\n```\n\n```go\nfunc (p *SSRFProtection) IsIPAccessAllowed(ip net.IP) bool\n```\nIsIPAccessAllowed 检查IP是否允许访问\n\n```go\nfunc (p *SSRFProtection) ResolveValidatedDialAddress(ctx context.Context, host string, port int) (string, error)\n```\nResolveValidatedDialAddress returns one validated address for callers that do not need multi-address fallback.\n\n```go\nfunc (p *SSRFProtection) ResolveValidatedDialAddresses(ctx context.Context, host string, port int) ([]string, error)\n```\n\n```go\nfunc (p *SSRFProtection) ValidateNetworkTarget(host string, port int) error\n```\n\n```go\nfunc (p *SSRFProtection) ValidateResolvedIP(host string, ip net.IP) error\n```\n\n```go\nfunc (p *SSRFProtection) ValidateURL(urlStr string) error\n```\nValidateURL 验证URL是否安全\n\n```go\ntype SystemStatus struct {\n\tCPUUsage    float64\n\tMemoryUsage float64\n\tDiskUsage   float64\n}\n```\nSystemStatus 系统状态信息\n\n```go\nfunc GetSystemStatus() SystemStatus\n```\nGetSystemStatus 获取当前系统状态\n\n","path":"github.com/MAX-API-Next/MAX-API/common","name":"common","synopsis":"","isRedistributable":true}
