Documentation
¶
Index ¶
- Constants
- Variables
- func Any2Type[T any](data any) (T, error)
- func ApiError(c *gin.Context, err error)
- func ApiErrorI18n(c *gin.Context, key string, args ...map[string]any)
- func ApiErrorMsg(c *gin.Context, msg string)
- func ApiSuccess(c *gin.Context, data any)
- func ApiSuccessI18n(c *gin.Context, key string, data any, args ...map[string]any)
- func BuildURL(base string, endpoint string) string
- func Bytes2Size(num int64) string
- func ChannelType2APIType(channelType int) (int, bool)
- func CleanupBodyStorage(c *gin.Context)
- func CleanupOldCacheFiles()
- func CleanupOldDiskCacheFiles(maxAge time.Duration) error
- func CreateDiskCacheFile(cacheType DiskCacheType) (string, *os.File, error)
- func DecodeJson(reader io.Reader, v any) error
- func DecrementDiskFiles(size int64)
- func DecrementMemoryBuffers(size int64)
- func DeepCopy[T any](src *T) (*T, error)
- func DeleteKey(key string, purpose string)
- func EmbedFolder(fsEmbed embed.FS, targetPath string) static.ServeFileSystem
- func EncodeBase64(str string) string
- func EnsureDiskCacheDir() error
- func FatalLog(v ...any)
- func GenerateBackupCodes() ([]string, error)
- func GenerateHMAC(data string) string
- func GenerateHMACWithKey(key []byte, data string) string
- func GenerateKey() (string, error)
- func GenerateQRCodeData(secret, username string) string
- func GenerateRandomCharsKey(length int) (string, error)
- func GenerateRandomKey(length int) (string, error)
- func GenerateTOTPSecret(accountName string) (*otp.Key, error)
- func GenerateVerificationCode(length int) string
- func Get2FAIssuer() string
- func GetAudioDuration(ctx context.Context, f io.ReadSeeker, ext string) (duration float64, err error)
- func GetContextKey(c *gin.Context, key constant.ContextKey) (any, bool)
- func GetContextKeyBool(c *gin.Context, key constant.ContextKey) bool
- func GetContextKeyInt(c *gin.Context, key constant.ContextKey) int
- func GetContextKeyString(c *gin.Context, key constant.ContextKey) string
- func GetContextKeyStringMap(c *gin.Context, key constant.ContextKey) map[string]any
- func GetContextKeyStringSlice(c *gin.Context, key constant.ContextKey) []string
- func GetContextKeyTime(c *gin.Context, key constant.ContextKey) time.Time
- func GetContextKeyType[T any](c *gin.Context, key constant.ContextKey) (T, bool)
- func GetDiskCacheDir() string
- func GetDiskCacheInfo() (fileCount int, totalSize int64, err error)
- func GetDiskCacheMaxSizeBytes() int64
- func GetDiskCachePath() string
- func GetDiskCacheThresholdBytes() int64
- func GetEndpointTypesByChannelType(channelType int, modelName string) []constant.EndpointType
- func GetEnvOrDefault(env string, defaultValue int) int
- func GetEnvOrDefaultBool(env string, defaultValue bool) bool
- func GetEnvOrDefaultString(env string, defaultValue string) string
- func GetIp() (ip string)
- func GetJsonString(data any) string
- func GetJsonType(data json.RawMessage) string
- func GetNetworkIps() []string
- func GetPointer[T any](v T) *T
- func GetRandomInt(max int) int
- func GetRandomString(length int) string
- func GetRequestBody(c *gin.Context) ([]byte, error)
- func GetStringIfEmpty(str string, defaultValue string) string
- func GetTimeString() string
- func GetTimestamp() int64
- func GetTopupGroupRatio(name string) float64
- func GetTrustQuota() int
- func GetUUID() string
- func HashBackupCode(code string) (string, error)
- func HmacSha256(message, key string) string
- func HmacSha256Raw(message, key []byte) []byte
- func IncrementDiskCacheHits()
- func IncrementDiskFiles(size int64)
- func IncrementMemoryBuffers(size int64)
- func IncrementMemoryCacheHits()
- func InitEnv()
- func InitRedisClient() (err error)
- func IntMax(a int, b int) int
- func Interface2String(inter interface{}) string
- func IsDiskCacheAvailable(requestSize int64) bool
- func IsDiskCacheEnabled() bool
- func IsIP(s string) bool
- func IsImageGenerationModel(modelName string) bool
- func IsIpInCIDRList(ip net.IP, cidrList []string) bool
- func IsJsonArray(str string) bool
- func IsJsonObject(str string) bool
- func IsOpenAIResponseOnlyModel(modelName string) bool
- func IsOpenAITextModel(modelName string) bool
- func IsPrivateIP(ip net.IP) bool
- func IsRequestBodyTooLargeError(err error) bool
- func IsRunningInContainer() bool
- func IsValidateRole(role int) bool
- func LogStartupSuccess(startTime time.Time, port string)
- func LoginAuth(username, password string) smtp.Auth
- func MapToJsonStr(m map[string]interface{}) string
- func Marshal(v any) ([]byte, error)
- func MaskEmail(email string) string
- func MaskSensitiveInfo(str string) string
- func Max(a int, b int) int
- func MessageWithRequestId(message string, id string) string
- func Monitor()
- func NormalizeBackupCode(code string) string
- func NormalizeBillingPreference(pref string) string
- func OpenBrowser(url string)
- func ParseIP(s string) net.IP
- func ParseMultipartFormReusable(c *gin.Context) (*multipart.Form, error)
- func ParseRedisOption() *redis.Options
- func Password2Hash(password string) (string, error)
- func RandomSleep()
- func ReadDiskCacheFile(filePath string) ([]byte, error)
- func ReadDiskCacheFileString(filePath string) (string, error)
- func RedisDel(key string) error
- func RedisDelKey(key string) error
- func RedisGet(key string) (string, error)
- func RedisHGetObj(key string, obj interface{}) error
- func RedisHIncrBy(key, field string, delta int64) error
- func RedisHSetField(key, field string, value interface{}) error
- func RedisHSetObj(key string, obj interface{}, expiration time.Duration) error
- func RedisIncr(key string, delta int64) error
- func RedisKeyCacheSeconds() int
- func RedisSet(key string, value string, expiration time.Duration) error
- func RegisterVerificationCodeWithKey(key string, code string, purpose string)
- func RelayCtxGo(ctx context.Context, f func())
- func RemoveDiskCacheFile(filePath string) error
- func ResetDiskCacheStats()
- func ResetDiskCacheUsage()
- func SafeSendBool(ch chan bool, value bool) (closed bool)
- func SafeSendString(ch chan string, value string) (closed bool)
- func SafeSendStringTimeout(ch chan string, value string, timeout int) (closed bool)
- func SaveTmpFile(filename string, data io.Reader) (string, error)
- func Seconds2Time(num int) (time string)
- func SendEmail(subject string, receiver string, content string) error
- func SetContextKey(c *gin.Context, key constant.ContextKey, value any)
- func SetDiskCacheConfig(config DiskCacheConfig)
- func SetPerformanceMonitorConfig(config PerformanceMonitorConfig)
- func Sha1(data []byte) string
- func Sha1Raw(data []byte) []byte
- func Sha256Raw(data []byte) []byte
- func ShouldUseDiskCache(dataSize int64) bool
- func StartPyroScope() error
- func StartSystemMonitor()
- func StrToJsonArray(str string) ([]interface{}, error)
- func StrToMap(str string) (map[string]interface{}, error)
- func String2Int(str string) int
- func StringToByteSlice(s string) []byte
- func StringsContains(strs []string, str string) bool
- func SyncDiskCacheStats()
- func SysError(s string)
- func SysLog(s string)
- func TopupGroupRatio2JSONString() string
- func UnescapeHTML(x string) interface{}
- func Unmarshal(data []byte, v any) error
- func UnmarshalBodyReusable(c *gin.Context, v any) error
- func UnmarshalJsonStr(data string, v any) error
- func UpdateTopupGroupRatioByJSONString(jsonStr string) error
- func ValidateBackupCode(code string) bool
- func ValidateNumericCode(code string) (string, error)
- func ValidatePasswordAndHash(password string, hash string) bool
- func ValidateRedirectURL(rawURL string) error
- func ValidateTOTPCode(secret, code string) bool
- func ValidateURLWithFetchSetting(urlStr string, enableSSRFProtection, allowPrivateIp bool, ...) error
- func VerifyCodeWithKey(key string, code string, purpose string) bool
- func WriteDiskCacheFile(cacheType DiskCacheType, data []byte) (string, error)
- func WriteDiskCacheFileString(cacheType DiskCacheType, data string) (string, error)
- type BodyStorage
- type CustomEvent
- type DiskCacheConfig
- type DiskCacheStats
- type DiskCacheType
- type DiskSpaceInfo
- type EndpointInfo
- type InMemoryRateLimiter
- type PageInfo
- type PerformanceMonitorConfig
- type SSRFProtection
- type SystemStatus
Constants ¶
const ( RoleGuestUser = 0 RoleCommonUser = 1 RoleAdminUser = 10 RoleRootUser = 100 )
const ( UserStatusEnabled = 1 // don't use 0, 0 is the default value! UserStatusDisabled = 2 // also don't use 0 )
const ( TokenStatusEnabled = 1 // don't use 0, 0 is the default value! TokenStatusDisabled = 2 // also don't use 0 TokenStatusExpired = 3 TokenStatusExhausted = 4 )
const ( RedemptionCodeStatusEnabled = 1 // don't use 0, 0 is the default value! RedemptionCodeStatusDisabled = 2 // also don't use 0 RedemptionCodeStatusUsed = 3 // also don't use 0 )
const ( ChannelStatusUnknown = 0 ChannelStatusEnabled = 1 // don't use 0, 0 is the default value! ChannelStatusManuallyDisabled = 2 // also don't use 0 ChannelStatusAutoDisabled = 3 )
const ( TopUpStatusPending = "pending" TopUpStatusSuccess = "success" TopUpStatusExpired = "expired" )
const ( DatabaseTypeMySQL = "mysql" DatabaseTypeSQLite = "sqlite" DatabaseTypePostgreSQL = "postgres" )
const ( // 备用码配置 BackupCodeLength = 8 // 备用码长度 BackupCodeCount = 4 // 生成备用码数量 // 限制配置 MaxFailAttempts = 5 // 最大失败尝试次数 LockoutDuration = 300 // 锁定时间(秒) )
const ( EmailVerificationPurpose = "v" PasswordResetPurpose = "r" )
const KeyBodyStorage = "key_body_storage"
const KeyRequestBody = "key_request_body"
const (
RequestIdKey = "X-Oneapi-Request-Id"
)
Variables ¶
var ( FileUploadPermission = RoleGuestUser FileDownloadPermission = RoleGuestUser ImageUploadPermission = RoleGuestUser ImageDownloadPermission = RoleGuestUser )
var ( GlobalApiRateLimitEnable bool GlobalApiRateLimitNum int GlobalApiRateLimitDuration int64 GlobalWebRateLimitEnable bool GlobalWebRateLimitNum int GlobalWebRateLimitDuration int64 CriticalRateLimitEnable bool CriticalRateLimitNum = 20 CriticalRateLimitDuration int64 = 20 * 60 UploadRateLimitNum = 10 UploadRateLimitDuration int64 = 60 DownloadRateLimitNum = 10 DownloadRateLimitDuration int64 = 60 // Per-user search rate limit (applies after authentication, keyed by user ID) SearchRateLimitNum = 10 SearchRateLimitDuration int64 = 60 )
All duration's unit is seconds Shouldn't larger then RateLimitKeyExpirationDuration
var ( Port = flag.Int("port", 3000, "the listening port") PrintVersion = flag.Bool("version", false, "print version and exit") PrintHelp = flag.Bool("help", false, "print help and exit") LogDir = flag.String("log-dir", "./logs", "specify the log directory") )
var ( // OpenAIResponseOnlyModels is a list of models that are only available for OpenAI responses. OpenAIResponseOnlyModels = []string{ "o3-pro", "o3-deep-research", "o4-mini-deep-research", } ImageGenerationModels = []string{ "dall-e-3", "dall-e-2", "gpt-image-1", "prefix:imagen-", "flux-", "flux.1-", } OpenAITextModels = []string{ "gpt-", "o1", "o3", "o4", "chatgpt", } )
var AutomaticDisableChannelEnabled = false
var AutomaticEnableChannelEnabled = false
var BatchUpdateEnabled = false
var BatchUpdateInterval int
var ChannelDisableThreshold = 5.0
var CohereSafetySetting string
https://docs.cohere.com/docs/safety-modes Type; NONE/CONTEXTUAL/STRICT
var CryptoSecret = uuid.New().String()
var DataExportDefaultTime = "hour" // unit: minute
var DataExportEnabled = true
var DataExportInterval = 5 // unit: minute
var DebugEnabled bool
var DefaultCollapseSidebar = false // default value of collapse sidebar
var DefaultSSRFProtection = &SSRFProtection{ AllowPrivateIp: false, DomainFilterMode: true, DomainList: []string{}, IpFilterMode: true, IpList: []string{}, AllowedPorts: []int{}, }
DefaultSSRFProtection 默认SSRF防护配置
var DisplayInCurrencyEnabled = true
保留旧变量以兼容历史逻辑,实际展示由 general_setting.quota_display_type 控制
var DisplayTokenStatEnabled = true
var DrawingEnabled = true
var EmailAliasRestrictionEnabled = false // 是否启用邮箱别名限制
var EmailDomainRestrictionEnabled = false // 是否启用邮箱域名限制
var EmailDomainWhitelist = []string{
"gmail.com",
"163.com",
"126.com",
"qq.com",
"outlook.com",
"hotmail.com",
"icloud.com",
"yahoo.com",
"foxmail.com",
}
var EmailLoginAuthServerList = []string{
"smtp.sendcloud.net",
"smtp.azurecomm.net",
}
var EmailVerificationEnabled = false
var ErrRequestBodyTooLarge = errors.New("request body too large")
var ErrStorageClosed = fmt.Errorf("body storage is closed")
ErrStorageClosed 存储已关闭错误
var GeminiSafetySetting string
var GitHubClientId = ""
var GitHubClientSecret = ""
var GitHubOAuthEnabled = false
var InsecureTLSConfig = &tls.Config{InsecureSkipVerify: true}
var IsMasterNode bool
var ItemsPerPage = 10
var LinuxDOClientId = ""
var LinuxDOClientSecret = ""
var LinuxDOMinimumTrustLevel = 0
var LinuxDOOAuthEnabled = false
var LogConsumeEnabled = true
var LogSqlType = DatabaseTypeSQLite // Default to SQLite for logging SQL queries
var Logo = ""
var MaxRecentItems = 1000
var MemoryCacheEnabled bool
var OptionMap map[string]string
var OptionMapRWMutex sync.RWMutex
var PasswordLoginEnabled = true
var PasswordRegisterEnabled = true
var PreConsumedQuota = 500
var QuotaForInvitee = 0
var QuotaForInviter = 0
var QuotaForNewUser = 0
var QuotaPerUnit = 500 * 1000.0 // $0.002 / 1K tokens
var ChatLink = "" var ChatLink2 = ""
var QuotaRemindThreshold = 1000
var RDB *redis.Client
var RateLimitKeyExpirationDuration = 20 * time.Minute
var RedisEnabled = true
var RegisterEnabled = true
var RelayMaxIdleConns int
var RelayMaxIdleConnsPerHost int
var RelayTimeout int // unit is second
var RequestInterval time.Duration
var RetryTimes = 0
var SMTPAccount = ""
var SMTPFrom = ""
var SMTPPort = 587
var SMTPSSLEnabled = false
var SMTPServer = ""
var SMTPToken = ""
var SQLitePath = "one-api.db?_busy_timeout=30000"
var SessionSecret = uuid.New().String()
var StartTime = time.Now().Unix() // unit: second
var SyncFrequency int // unit is second
var SystemName = "New API"
var TLSInsecureSkipVerify bool
var TaskEnabled = true
var TelegramBotName = ""
var TelegramBotToken = ""
var TelegramOAuthEnabled = false
var TopUpLink = ""
var TopupGroupRatio = map[string]float64{
"default": 1,
"vip": 1,
"svip": 1,
}
TranslateMessage 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
var TurnstileCheckEnabled = false
var TurnstileSecretKey = ""
var TurnstileSiteKey = ""
var UsingClickHouse = false
var UsingMySQL = false
var UsingPostgreSQL = false
var UsingSQLite = false
var Validate *validator.Validate
var VerificationValidMinutes = 10
var Version = "v0.0.0" // this hard coding will be replaced automatically when building, no need to manually change
var WeChatAccountQRCodeImageURL = ""
var WeChatAuthEnabled = false
var WeChatServerAddress = ""
var WeChatServerToken = ""
Functions ¶
func ApiErrorI18n ¶ added in v0.10.8
ApiErrorI18n returns a translated error message based on the user's language preference key is the i18n message key, args is optional template data
func ApiErrorMsg ¶
func ApiSuccess ¶
func ApiSuccessI18n ¶ added in v0.10.8
ApiSuccessI18n returns a translated success message based on the user's language preference
func Bytes2Size ¶
func ChannelType2APIType ¶
func CleanupBodyStorage ¶
CleanupBodyStorage 清理请求体存储(应在请求结束时调用)
func CleanupOldDiskCacheFiles ¶ added in v0.10.8
CleanupOldDiskCacheFiles 清理旧的缓存文件 maxAge: 文件最大存活时间 注意:此函数只删除文件,不更新统计(因为无法知道每个文件的原始大小)
func CreateDiskCacheFile ¶ added in v0.10.8
func CreateDiskCacheFile(cacheType DiskCacheType) (string, *os.File, error)
CreateDiskCacheFile 创建磁盘缓存文件 cacheType: 缓存类型(body/file) 返回文件路径和文件句柄
func DecrementMemoryBuffers ¶
func DecrementMemoryBuffers(size int64)
DecrementMemoryBuffers 减少内存缓存计数
func EmbedFolder ¶
func EmbedFolder(fsEmbed embed.FS, targetPath string) static.ServeFileSystem
func EncodeBase64 ¶
func EnsureDiskCacheDir ¶ added in v0.10.8
func EnsureDiskCacheDir() error
EnsureDiskCacheDir 确保缓存目录存在
func GenerateHMAC ¶
func GenerateHMACWithKey ¶
func GenerateKey ¶
func GenerateQRCodeData ¶
GenerateQRCodeData 生成二维码数据
func GenerateRandomCharsKey ¶
func GenerateRandomKey ¶
func GenerateTOTPSecret ¶
GenerateTOTPSecret 生成TOTP密钥和配置
func GetAudioDuration ¶
func GetAudioDuration(ctx context.Context, f io.ReadSeeker, ext string) (duration float64, err error)
GetAudioDuration 使用纯 Go 库获取音频文件的时长(秒)。 它不再依赖外部的 ffmpeg 或 ffprobe 程序。
func GetContextKey ¶
func GetContextKeyBool ¶
func GetContextKeyBool(c *gin.Context, key constant.ContextKey) bool
func GetContextKeyInt ¶
func GetContextKeyInt(c *gin.Context, key constant.ContextKey) int
func GetContextKeyString ¶
func GetContextKeyString(c *gin.Context, key constant.ContextKey) string
func GetContextKeyStringMap ¶
func GetContextKeyStringSlice ¶
func GetContextKeyStringSlice(c *gin.Context, key constant.ContextKey) []string
func GetContextKeyTime ¶
func GetContextKeyType ¶
func GetDiskCacheDir ¶ added in v0.10.8
func GetDiskCacheDir() string
GetDiskCacheDir 获取统一的磁盘缓存目录 注意:每次调用都会重新计算,以响应配置变化
func GetDiskCacheInfo ¶ added in v0.10.8
GetDiskCacheInfo 获取磁盘缓存目录信息
func GetDiskCacheMaxSizeBytes ¶
func GetDiskCacheMaxSizeBytes() int64
GetDiskCacheMaxSizeBytes 获取磁盘缓存最大大小(字节)
func GetDiskCacheThresholdBytes ¶
func GetDiskCacheThresholdBytes() int64
GetDiskCacheThresholdBytes 获取磁盘缓存阈值(字节)
func GetEndpointTypesByChannelType ¶
func GetEndpointTypesByChannelType(channelType int, modelName string) []constant.EndpointType
GetEndpointTypesByChannelType 获取渠道最优先端点类型(所有的渠道都支持 OpenAI 端点)
func GetEnvOrDefault ¶
func GetEnvOrDefaultBool ¶
func GetEnvOrDefaultString ¶
func GetJsonString ¶
func GetJsonType ¶
func GetJsonType(data json.RawMessage) string
func GetNetworkIps ¶
func GetNetworkIps() []string
func GetPointer ¶
func GetPointer[T any](v T) *T
func GetRandomInt ¶
func GetRandomString ¶
func GetStringIfEmpty ¶
func GetTimeString ¶
func GetTimeString() string
func GetTimestamp ¶
func GetTimestamp() int64
func GetTopupGroupRatio ¶
func GetTrustQuota ¶
func GetTrustQuota() int
func HmacSha256 ¶
func HmacSha256Raw ¶
func IncrementMemoryBuffers ¶
func IncrementMemoryBuffers(size int64)
IncrementMemoryBuffers 增加内存缓存计数
func InitRedisClient ¶
func InitRedisClient() (err error)
InitRedisClient This function is called after init()
func Interface2String ¶
func Interface2String(inter interface{}) string
func IsDiskCacheAvailable ¶
IsDiskCacheAvailable 检查是否可以创建新的磁盘缓存
func IsImageGenerationModel ¶
func IsJsonArray ¶
func IsJsonObject ¶
func IsOpenAITextModel ¶
func IsPrivateIP ¶
func IsRunningInContainer ¶
func IsRunningInContainer() bool
IsRunningInContainer detects if the application is running inside a container
func IsValidateRole ¶
func LogStartupSuccess ¶
func MapToJsonStr ¶
func MaskEmail ¶
MaskEmail masks a user email to prevent PII leakage in logs Returns "***masked***" if email is empty, otherwise shows only the domain part
func MaskSensitiveInfo ¶
MaskSensitiveInfo masks sensitive information like URLs, IPs, and domain names in a string Example: http://example.com -> http://***.com https://api.test.org/v1/users/123?key=secret -> https://***.org/***/***/?key=*** https://sub.domain.co.uk/path/to/resource -> https://***.co.uk/***/*** 192.168.1.1 -> ***.***.***.*** openai.com -> ***.com www.openai.com -> ***.***.com api.openai.com -> ***.***.com
func MessageWithRequestId ¶
func NormalizeBackupCode ¶
NormalizeBackupCode 标准化备用码格式
func NormalizeBillingPreference ¶ added in v0.10.8
NormalizeBillingPreference clamps the billing preference to valid values.
func OpenBrowser ¶
func OpenBrowser(url string)
func ParseRedisOption ¶
func Password2Hash ¶
func RandomSleep ¶
func RandomSleep()
func ReadDiskCacheFile ¶ added in v0.10.8
ReadDiskCacheFile 读取磁盘缓存文件
func ReadDiskCacheFileString ¶ added in v0.10.8
ReadDiskCacheFileString 读取磁盘缓存文件为字符串
func RedisDelKey ¶
func RedisHGetObj ¶
func RedisHIncrBy ¶
func RedisHSetField ¶
func RedisKeyCacheSeconds ¶
func RedisKeyCacheSeconds() int
func RelayCtxGo ¶
func RemoveDiskCacheFile ¶ added in v0.10.8
RemoveDiskCacheFile 删除磁盘缓存文件
func ResetDiskCacheUsage ¶ added in v0.10.8
func ResetDiskCacheUsage()
ResetDiskCacheUsage 重置磁盘缓存使用量统计(用于清理缓存后)
func SafeSendBool ¶
func SafeSendString ¶
func SafeSendStringTimeout ¶
SafeSendStringTimeout send, return true, else return false
func SaveTmpFile ¶
SaveTmpFile saves data to a temporary file. The filename would be apppended with a random string.
func Seconds2Time ¶
func SetContextKey ¶
func SetContextKey(c *gin.Context, key constant.ContextKey, value any)
func SetDiskCacheConfig ¶
func SetDiskCacheConfig(config DiskCacheConfig)
SetDiskCacheConfig 设置磁盘缓存配置
func SetPerformanceMonitorConfig ¶ added in v0.10.8
func SetPerformanceMonitorConfig(config PerformanceMonitorConfig)
SetPerformanceMonitorConfig 设置性能监控配置
func ShouldUseDiskCache ¶ added in v0.10.8
ShouldUseDiskCache 判断是否应该使用磁盘缓存
func StartPyroScope ¶
func StartPyroScope() error
func StrToJsonArray ¶
func String2Int ¶
func StringToByteSlice ¶
StringToByteSlice []byte only read, panic on append
func StringsContains ¶
func SyncDiskCacheStats ¶ added in v0.10.8
func SyncDiskCacheStats()
SyncDiskCacheStats 从实际磁盘状态同步统计信息 用于修正统计与实际不符的情况
func TopupGroupRatio2JSONString ¶
func TopupGroupRatio2JSONString() string
func UnescapeHTML ¶
func UnescapeHTML(x string) interface{}
func UnmarshalJsonStr ¶
func ValidateNumericCode ¶
ValidateNumericCode 验证数字验证码格式
func ValidatePasswordAndHash ¶
func ValidateRedirectURL ¶
ValidateRedirectURL validates that a redirect URL is safe to use. It checks that:
- The URL is properly formatted
- The scheme is either http or https
- The domain is in the trusted domains list (exact match or subdomain)
Returns nil if the URL is valid and trusted, otherwise returns an error describing why the validation failed.
func ValidateURLWithFetchSetting ¶
func ValidateURLWithFetchSetting(urlStr string, enableSSRFProtection, allowPrivateIp bool, domainFilterMode bool, ipFilterMode bool, domainList, ipList, allowedPorts []string, applyIPFilterForDomain bool) error
ValidateURLWithFetchSetting 使用FetchSetting配置验证URL
func WriteDiskCacheFile ¶ added in v0.10.8
func WriteDiskCacheFile(cacheType DiskCacheType, data []byte) (string, error)
WriteDiskCacheFile 写入数据到磁盘缓存文件 返回文件路径
func WriteDiskCacheFileString ¶ added in v0.10.8
func WriteDiskCacheFileString(cacheType DiskCacheType, data string) (string, error)
WriteDiskCacheFileString 写入字符串到磁盘缓存文件
Types ¶
type BodyStorage ¶
type BodyStorage interface {
io.ReadSeeker
io.Closer
// Bytes 获取全部内容
Bytes() ([]byte, error)
// Size 获取数据大小
Size() int64
// IsDisk 是否是磁盘存储
IsDisk() bool
}
BodyStorage 请求体存储接口
func CreateBodyStorage ¶
func CreateBodyStorage(data []byte) (BodyStorage, error)
CreateBodyStorage 根据数据大小创建合适的存储
func CreateBodyStorageFromReader ¶
func CreateBodyStorageFromReader(reader io.Reader, contentLength int64, maxBytes int64) (BodyStorage, error)
CreateBodyStorageFromReader 从 Reader 创建存储(用于大请求的流式处理)
func GetBodyStorage ¶
func GetBodyStorage(c *gin.Context) (BodyStorage, error)
GetBodyStorage 获取请求体存储对象(用于需要多次读取的场景)
type CustomEvent ¶
func (CustomEvent) Render ¶
func (r CustomEvent) Render(w http.ResponseWriter) error
func (CustomEvent) WriteContentType ¶
func (r CustomEvent) WriteContentType(w http.ResponseWriter)
type DiskCacheConfig ¶
type DiskCacheConfig struct {
// Enabled 是否启用磁盘缓存
Enabled bool
// ThresholdMB 触发磁盘缓存的请求体大小阈值(MB)
ThresholdMB int
// MaxSizeMB 磁盘缓存最大总大小(MB)
MaxSizeMB int
// Path 磁盘缓存目录
Path string
}
DiskCacheConfig 磁盘缓存配置(由 performance_setting 包更新)
type DiskCacheStats ¶
type DiskCacheStats struct {
// 当前活跃的磁盘缓存文件数
ActiveDiskFiles int64 `json:"active_disk_files"`
// 当前磁盘缓存总大小(字节)
CurrentDiskUsageBytes int64 `json:"current_disk_usage_bytes"`
// 当前内存缓存数量
ActiveMemoryBuffers int64 `json:"active_memory_buffers"`
// 当前内存缓存总大小(字节)
CurrentMemoryUsageBytes int64 `json:"current_memory_usage_bytes"`
// 磁盘缓存命中次数
DiskCacheHits int64 `json:"disk_cache_hits"`
// 内存缓存命中次数
MemoryCacheHits int64 `json:"memory_cache_hits"`
// 磁盘缓存最大限制(字节)
DiskCacheMaxBytes int64 `json:"disk_cache_max_bytes"`
// 磁盘缓存阈值(字节)
DiskCacheThresholdBytes int64 `json:"disk_cache_threshold_bytes"`
}
DiskCacheStats 磁盘缓存统计信息
type DiskCacheType ¶ added in v0.10.8
type DiskCacheType string
DiskCacheType 磁盘缓存类型
const ( DiskCacheTypeBody DiskCacheType = "body" // 请求体缓存 DiskCacheTypeFile DiskCacheType = "file" // 文件数据缓存 )
type DiskSpaceInfo ¶ added in v0.10.8
type DiskSpaceInfo struct {
// 总空间(字节)
Total uint64 `json:"total"`
// 可用空间(字节)
Free uint64 `json:"free"`
// 已用空间(字节)
Used uint64 `json:"used"`
// 使用百分比
UsedPercent float64 `json:"used_percent"`
}
DiskSpaceInfo 磁盘空间信息
func GetDiskSpaceInfo ¶ added in v0.10.8
func GetDiskSpaceInfo() DiskSpaceInfo
GetDiskSpaceInfo 获取缓存目录所在磁盘的空间信息 (Unix/Linux/macOS)
type EndpointInfo ¶
func GetDefaultEndpointInfo ¶
func GetDefaultEndpointInfo(et constant.EndpointType) (EndpointInfo, bool)
GetDefaultEndpointInfo 返回指定端点类型的默认信息以及是否存在
type InMemoryRateLimiter ¶
type InMemoryRateLimiter struct {
// contains filtered or unexported fields
}
func (*InMemoryRateLimiter) Init ¶
func (l *InMemoryRateLimiter) Init(expirationDuration time.Duration)
type PageInfo ¶
type PageInfo struct {
Page int `json:"page"` // page num 页码
PageSize int `json:"page_size"` // page size 页大小
Total int `json:"total"` // 总条数,后设置
Items any `json:"items"` // 数据,后设置
}
func GetPageQuery ¶
func (*PageInfo) GetPageSize ¶
func (*PageInfo) GetStartIdx ¶
type PerformanceMonitorConfig ¶ added in v0.10.8
type PerformanceMonitorConfig struct {
Enabled bool
CPUThreshold int
MemoryThreshold int
DiskThreshold int
}
PerformanceMonitorConfig 性能监控配置
func GetPerformanceMonitorConfig ¶ added in v0.10.8
func GetPerformanceMonitorConfig() PerformanceMonitorConfig
GetPerformanceMonitorConfig 获取性能监控配置
type SSRFProtection ¶
type SSRFProtection struct {
AllowPrivateIp bool
DomainFilterMode bool // true: 白名单, false: 黑名单
DomainList []string // domain format, e.g. example.com, *.example.com
IpFilterMode bool // true: 白名单, false: 黑名单
IpList []string // CIDR or single IP
AllowedPorts []int // 允许的端口范围
ApplyIPFilterForDomain bool // 对域名启用IP过滤
}
SSRFProtection SSRF防护配置
func (*SSRFProtection) IsIPAccessAllowed ¶
func (p *SSRFProtection) IsIPAccessAllowed(ip net.IP) bool
IsIPAccessAllowed 检查IP是否允许访问
func (*SSRFProtection) ValidateURL ¶
func (p *SSRFProtection) ValidateURL(urlStr string) error
ValidateURL 验证URL是否安全
type SystemStatus ¶ added in v0.10.8
SystemStatus 系统状态信息
func GetSystemStatus ¶ added in v0.10.8
func GetSystemStatus() SystemStatus
GetSystemStatus 获取当前系统状态
Source Files
¶
- api_type.go
- audio.go
- body_storage.go
- constants.go
- copy.go
- crypto.go
- custom-event.go
- database.go
- disk_cache.go
- disk_cache_config.go
- email-outlook-auth.go
- email.go
- embed-file-system.go
- endpoint_defaults.go
- endpoint_type.go
- env.go
- gin.go
- go-channel.go
- gopool.go
- hash.go
- init.go
- ip.go
- json.go
- model.go
- page_info.go
- performance_config.go
- pprof.go
- pyro.go
- quota.go
- rate-limit.go
- redis.go
- ssrf_protection.go
- str.go
- sys_log.go
- system_monitor.go
- system_monitor_unix.go
- topup-ratio.go
- totp.go
- url_validator.go
- utils.go
- validate.go
- verification.go