common

package
v0.10.8-alpha.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 3, 2026 License: AGPL-3.0 Imports: 65 Imported by: 0

Documentation

Index

Constants

View Source
const (
	RoleGuestUser  = 0
	RoleCommonUser = 1
	RoleAdminUser  = 10
	RoleRootUser   = 100
)
View Source
const (
	UserStatusEnabled  = 1 // don't use 0, 0 is the default value!
	UserStatusDisabled = 2 // also don't use 0
)
View Source
const (
	TokenStatusEnabled   = 1 // don't use 0, 0 is the default value!
	TokenStatusDisabled  = 2 // also don't use 0
	TokenStatusExpired   = 3
	TokenStatusExhausted = 4
)
View Source
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
)
View Source
const (
	ChannelStatusUnknown          = 0
	ChannelStatusEnabled          = 1 // don't use 0, 0 is the default value!
	ChannelStatusManuallyDisabled = 2 // also don't use 0
	ChannelStatusAutoDisabled     = 3
)
View Source
const (
	TopUpStatusPending = "pending"
	TopUpStatusSuccess = "success"
	TopUpStatusExpired = "expired"
)
View Source
const (
	DatabaseTypeMySQL      = "mysql"
	DatabaseTypeSQLite     = "sqlite"
	DatabaseTypePostgreSQL = "postgres"
)
View Source
const (
	// 备用码配置
	BackupCodeLength = 8 // 备用码长度
	BackupCodeCount  = 4 // 生成备用码数量

	// 限制配置
	MaxFailAttempts = 5   // 最大失败尝试次数
	LockoutDuration = 300 // 锁定时间(秒)
)
View Source
const (
	EmailVerificationPurpose = "v"
	PasswordResetPurpose     = "r"
)
View Source
const KeyBodyStorage = "key_body_storage"
View Source
const KeyRequestBody = "key_request_body"
View Source
const (
	RequestIdKey = "X-Oneapi-Request-Id"
)

Variables

View Source
var (
	FileUploadPermission    = RoleGuestUser
	FileDownloadPermission  = RoleGuestUser
	ImageUploadPermission   = RoleGuestUser
	ImageDownloadPermission = RoleGuestUser
)
View Source
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
)

All duration's unit is seconds Shouldn't larger then RateLimitKeyExpirationDuration

View Source
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")
)
View Source
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",
	}
)
View Source
var AutomaticDisableChannelEnabled = false
View Source
var AutomaticEnableChannelEnabled = false
View Source
var BatchUpdateEnabled = false
View Source
var BatchUpdateInterval int
View Source
var ChannelDisableThreshold = 5.0
View Source
var CohereSafetySetting string

https://docs.cohere.com/docs/safety-modes Type; NONE/CONTEXTUAL/STRICT

View Source
var CryptoSecret = uuid.New().String()
View Source
var DataExportDefaultTime = "hour" // unit: minute
View Source
var DataExportEnabled = true
View Source
var DataExportInterval = 5 // unit: minute
View Source
var DebugEnabled bool
View Source
var DefaultCollapseSidebar = false // default value of collapse sidebar
View Source
var DefaultSSRFProtection = &SSRFProtection{
	AllowPrivateIp:   false,
	DomainFilterMode: true,
	DomainList:       []string{},
	IpFilterMode:     true,
	IpList:           []string{},
	AllowedPorts:     []int{},
}

DefaultSSRFProtection 默认SSRF防护配置

View Source
var DisplayInCurrencyEnabled = true

保留旧变量以兼容历史逻辑,实际展示由 general_setting.quota_display_type 控制

View Source
var DisplayTokenStatEnabled = true
View Source
var DrawingEnabled = true
View Source
var EmailAliasRestrictionEnabled = false // 是否启用邮箱别名限制
View Source
var EmailDomainRestrictionEnabled = false // 是否启用邮箱域名限制
View Source
var EmailDomainWhitelist = []string{
	"gmail.com",
	"163.com",
	"126.com",
	"qq.com",
	"outlook.com",
	"hotmail.com",
	"icloud.com",
	"yahoo.com",
	"foxmail.com",
}
View Source
var EmailLoginAuthServerList = []string{
	"smtp.sendcloud.net",
	"smtp.azurecomm.net",
}
View Source
var EmailVerificationEnabled = false
View Source
var ErrRequestBodyTooLarge = errors.New("request body too large")
View Source
var ErrStorageClosed = fmt.Errorf("body storage is closed")

ErrStorageClosed 存储已关闭错误

View Source
var Footer = ""
View Source
var GeminiSafetySetting string
View Source
var GitHubClientId = ""
View Source
var GitHubClientSecret = ""
View Source
var GitHubOAuthEnabled = false
View Source
var InsecureTLSConfig = &tls.Config{InsecureSkipVerify: true}
View Source
var IsMasterNode bool
View Source
var ItemsPerPage = 10
View Source
var LinuxDOClientId = ""
View Source
var LinuxDOClientSecret = ""
View Source
var LinuxDOMinimumTrustLevel = 0
View Source
var LinuxDOOAuthEnabled = false
View Source
var LogConsumeEnabled = true
View Source
var LogSqlType = DatabaseTypeSQLite // Default to SQLite for logging SQL queries
View Source
View Source
var MaxRecentItems = 100
View Source
var MemoryCacheEnabled bool
View Source
var OptionMap map[string]string
View Source
var OptionMapRWMutex sync.RWMutex
View Source
var PasswordLoginEnabled = true
View Source
var PasswordRegisterEnabled = true
View Source
var PreConsumedQuota = 500
View Source
var QuotaForInvitee = 0
View Source
var QuotaForInviter = 0
View Source
var QuotaForNewUser = 0
View Source
var QuotaPerUnit = 500 * 1000.0 // $0.002 / 1K tokens

var ChatLink = "" var ChatLink2 = ""

View Source
var QuotaRemindThreshold = 1000
View Source
var RateLimitKeyExpirationDuration = 20 * time.Minute
View Source
var RedisEnabled = true
View Source
var RegisterEnabled = true
View Source
var RelayMaxIdleConns int
View Source
var RelayMaxIdleConnsPerHost int
View Source
var RelayTimeout int // unit is second
View Source
var RequestInterval time.Duration
View Source
var RetryTimes = 0
View Source
var SMTPAccount = ""
View Source
var SMTPFrom = ""
View Source
var SMTPPort = 587
View Source
var SMTPSSLEnabled = false
View Source
var SMTPServer = ""
View Source
var SMTPToken = ""
View Source
var SQLitePath = "one-api.db?_busy_timeout=30000"
View Source
var SessionSecret = uuid.New().String()
View Source
var StartTime = time.Now().Unix() // unit: second
View Source
var SyncFrequency int // unit is second
View Source
var SystemName = "New API"
View Source
var TLSInsecureSkipVerify bool
View Source
var TaskEnabled = true
View Source
var TelegramBotName = ""
View Source
var TelegramBotToken = ""
View Source
var TelegramOAuthEnabled = false
View Source
var TopUpLink = ""
View Source
var TopupGroupRatio = map[string]float64{
	"default": 1,
	"vip":     1,
	"svip":    1,
}
View Source
var TurnstileCheckEnabled = false
View Source
var TurnstileSecretKey = ""
View Source
var TurnstileSiteKey = ""
View Source
var UsingClickHouse = false
View Source
var UsingMySQL = false
View Source
var UsingPostgreSQL = false
View Source
var UsingSQLite = false
View Source
var VerificationValidMinutes = 10
View Source
var Version = "v0.0.0" // this hard coding will be replaced automatically when building, no need to manually change
View Source
var WeChatAccountQRCodeImageURL = ""
View Source
var WeChatAuthEnabled = false
View Source
var WeChatServerAddress = ""
View Source
var WeChatServerToken = ""

Functions

func Any2Type

func Any2Type[T any](data any) (T, error)

func ApiError

func ApiError(c *gin.Context, err error)

func ApiErrorMsg

func ApiErrorMsg(c *gin.Context, msg string)

func ApiSuccess

func ApiSuccess(c *gin.Context, data any)

func BuildURL

func BuildURL(base string, endpoint string) string

BuildURL concatenates base and endpoint, returns the complete url string

func Bytes2Size

func Bytes2Size(num int64) string

func ChannelType2APIType

func ChannelType2APIType(channelType int) (int, bool)

func CleanupBodyStorage

func CleanupBodyStorage(c *gin.Context)

CleanupBodyStorage 清理请求体存储(应在请求结束时调用)

func CleanupOldCacheFiles

func CleanupOldCacheFiles()

CleanupOldCacheFiles 清理旧的缓存文件(用于启动时清理残留)

func DecodeJson

func DecodeJson(reader io.Reader, v any) error

func DecrementDiskFiles

func DecrementDiskFiles(size int64)

DecrementDiskFiles 减少磁盘文件计数

func DecrementMemoryBuffers

func DecrementMemoryBuffers(size int64)

DecrementMemoryBuffers 减少内存缓存计数

func DeepCopy

func DeepCopy[T any](src *T) (*T, error)

func DeleteKey

func DeleteKey(key string, purpose string)

func EmbedFolder

func EmbedFolder(fsEmbed embed.FS, targetPath string) static.ServeFileSystem

func EncodeBase64

func EncodeBase64(str string) string

func FatalLog

func FatalLog(v ...any)

func GenerateBackupCodes

func GenerateBackupCodes() ([]string, error)

GenerateBackupCodes 生成备用恢复码

func GenerateHMAC

func GenerateHMAC(data string) string

func GenerateHMACWithKey

func GenerateHMACWithKey(key []byte, data string) string

func GenerateKey

func GenerateKey() (string, error)

func GenerateQRCodeData

func GenerateQRCodeData(secret, username string) string

GenerateQRCodeData 生成二维码数据

func GenerateRandomCharsKey

func GenerateRandomCharsKey(length int) (string, error)

func GenerateRandomKey

func GenerateRandomKey(length int) (string, error)

func GenerateTOTPSecret

func GenerateTOTPSecret(accountName string) (*otp.Key, error)

GenerateTOTPSecret 生成TOTP密钥和配置

func GenerateVerificationCode

func GenerateVerificationCode(length int) string

func Get2FAIssuer

func Get2FAIssuer() string

Get2FAIssuer 获取2FA发行者名称

func GetAudioDuration

func GetAudioDuration(ctx context.Context, f io.ReadSeeker, ext string) (duration float64, err error)

GetAudioDuration 使用纯 Go 库获取音频文件的时长(秒)。 它不再依赖外部的 ffmpeg 或 ffprobe 程序。

func GetContextKey

func GetContextKey(c *gin.Context, key constant.ContextKey) (any, bool)

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 GetContextKeyStringMap(c *gin.Context, key constant.ContextKey) map[string]any

func GetContextKeyStringSlice

func GetContextKeyStringSlice(c *gin.Context, key constant.ContextKey) []string

func GetContextKeyTime

func GetContextKeyTime(c *gin.Context, key constant.ContextKey) time.Time

func GetContextKeyType

func GetContextKeyType[T any](c *gin.Context, key constant.ContextKey) (T, bool)

func GetDiskCacheMaxSizeBytes

func GetDiskCacheMaxSizeBytes() int64

GetDiskCacheMaxSizeBytes 获取磁盘缓存最大大小(字节)

func GetDiskCachePath

func GetDiskCachePath() string

GetDiskCachePath 获取磁盘缓存目录

func GetDiskCacheThresholdBytes

func GetDiskCacheThresholdBytes() int64

GetDiskCacheThresholdBytes 获取磁盘缓存阈值(字节)

func GetEndpointTypesByChannelType

func GetEndpointTypesByChannelType(channelType int, modelName string) []constant.EndpointType

GetEndpointTypesByChannelType 获取渠道最优先端点类型(所有的渠道都支持 OpenAI 端点)

func GetEnvOrDefault

func GetEnvOrDefault(env string, defaultValue int) int

func GetEnvOrDefaultBool

func GetEnvOrDefaultBool(env string, defaultValue bool) bool

func GetEnvOrDefaultString

func GetEnvOrDefaultString(env string, defaultValue string) string

func GetIp

func GetIp() (ip string)

func GetJsonString

func GetJsonString(data any) string

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 GetRandomInt(max int) int

func GetRandomString

func GetRandomString(length int) string

func GetRequestBody

func GetRequestBody(c *gin.Context) ([]byte, error)

func GetStringIfEmpty

func GetStringIfEmpty(str string, defaultValue string) string

func GetTimeString

func GetTimeString() string

func GetTimestamp

func GetTimestamp() int64

func GetTopupGroupRatio

func GetTopupGroupRatio(name string) float64

func GetTrustQuota

func GetTrustQuota() int

func GetUUID

func GetUUID() string

func HashBackupCode

func HashBackupCode(code string) (string, error)

HashBackupCode 对备用码进行哈希

func HmacSha256

func HmacSha256(message, key string) string

func HmacSha256Raw

func HmacSha256Raw(message, key []byte) []byte

func IncrementDiskCacheHits

func IncrementDiskCacheHits()

IncrementDiskCacheHits 增加磁盘缓存命中次数

func IncrementDiskFiles

func IncrementDiskFiles(size int64)

IncrementDiskFiles 增加磁盘文件计数

func IncrementMemoryBuffers

func IncrementMemoryBuffers(size int64)

IncrementMemoryBuffers 增加内存缓存计数

func IncrementMemoryCacheHits

func IncrementMemoryCacheHits()

IncrementMemoryCacheHits 增加内存缓存命中次数

func InitEnv

func InitEnv()

func InitRedisClient

func InitRedisClient() (err error)

InitRedisClient This function is called after init()

func IntMax

func IntMax(a int, b int) int

func Interface2String

func Interface2String(inter interface{}) string

func IsDiskCacheAvailable

func IsDiskCacheAvailable(requestSize int64) bool

IsDiskCacheAvailable 检查是否可以创建新的磁盘缓存

func IsDiskCacheEnabled

func IsDiskCacheEnabled() bool

IsDiskCacheEnabled 是否启用磁盘缓存

func IsIP

func IsIP(s string) bool

func IsImageGenerationModel

func IsImageGenerationModel(modelName string) bool

func IsIpInCIDRList

func IsIpInCIDRList(ip net.IP, cidrList []string) bool

func IsJsonArray

func IsJsonArray(str string) bool

func IsJsonObject

func IsJsonObject(str string) bool

func IsOpenAIResponseOnlyModel

func IsOpenAIResponseOnlyModel(modelName string) bool

func IsOpenAITextModel

func IsOpenAITextModel(modelName string) bool

func IsPrivateIP

func IsPrivateIP(ip net.IP) bool

func IsRequestBodyTooLargeError

func IsRequestBodyTooLargeError(err error) bool

func IsRunningInContainer

func IsRunningInContainer() bool

IsRunningInContainer detects if the application is running inside a container

func IsValidateRole

func IsValidateRole(role int) bool

func LogStartupSuccess

func LogStartupSuccess(startTime time.Time, port string)

func LoginAuth

func LoginAuth(username, password string) smtp.Auth

func MapToJsonStr

func MapToJsonStr(m map[string]interface{}) string

func Marshal

func Marshal(v any) ([]byte, error)

func MaskEmail

func MaskEmail(email string) string

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

func MaskSensitiveInfo(str string) string

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 Max

func Max(a int, b int) int

func MessageWithRequestId

func MessageWithRequestId(message string, id string) string

func Monitor

func Monitor()

Monitor 定时监控cpu使用率,超过阈值输出pprof文件

func NormalizeBackupCode

func NormalizeBackupCode(code string) string

NormalizeBackupCode 标准化备用码格式

func NormalizeBillingPreference added in v0.10.8

func NormalizeBillingPreference(pref string) string

NormalizeBillingPreference clamps the billing preference to valid values.

func OpenBrowser

func OpenBrowser(url string)

func ParseIP

func ParseIP(s string) net.IP

func ParseMultipartFormReusable

func ParseMultipartFormReusable(c *gin.Context) (*multipart.Form, error)

func ParseRedisOption

func ParseRedisOption() *redis.Options

func Password2Hash

func Password2Hash(password string) (string, error)

func RandomSleep

func RandomSleep()

func RedisDel

func RedisDel(key string) error

func RedisDelKey

func RedisDelKey(key string) error

func RedisGet

func RedisGet(key string) (string, error)

func RedisHGetObj

func RedisHGetObj(key string, obj interface{}) error

func RedisHIncrBy

func RedisHIncrBy(key, field string, delta int64) error

func RedisHSetField

func RedisHSetField(key, field string, value interface{}) error

func RedisHSetObj

func RedisHSetObj(key string, obj interface{}, expiration time.Duration) error

func RedisIncr

func RedisIncr(key string, delta int64) error

RedisIncr Add this function to handle atomic increments

func RedisKeyCacheSeconds

func RedisKeyCacheSeconds() int

func RedisSet

func RedisSet(key string, value string, expiration time.Duration) error

func RegisterVerificationCodeWithKey

func RegisterVerificationCodeWithKey(key string, code string, purpose string)

func RelayCtxGo

func RelayCtxGo(ctx context.Context, f func())

func ResetDiskCacheStats

func ResetDiskCacheStats()

ResetDiskCacheStats 重置统计信息(不重置当前使用量)

func SafeSendBool

func SafeSendBool(ch chan bool, value bool) (closed bool)

func SafeSendString

func SafeSendString(ch chan string, value string) (closed bool)

func SafeSendStringTimeout

func SafeSendStringTimeout(ch chan string, value string, timeout int) (closed bool)

SafeSendStringTimeout send, return true, else return false

func SaveTmpFile

func SaveTmpFile(filename string, data io.Reader) (string, error)

SaveTmpFile saves data to a temporary file. The filename would be apppended with a random string.

func Seconds2Time

func Seconds2Time(num int) (time string)

func SendEmail

func SendEmail(subject string, receiver string, content string) error

func SetContextKey

func SetContextKey(c *gin.Context, key constant.ContextKey, value any)

func SetDiskCacheConfig

func SetDiskCacheConfig(config DiskCacheConfig)

SetDiskCacheConfig 设置磁盘缓存配置

func Sha1

func Sha1(data []byte) string

func Sha1Raw

func Sha1Raw(data []byte) []byte

func Sha256Raw

func Sha256Raw(data []byte) []byte

func StartPyroScope

func StartPyroScope() error

func StrToJsonArray

func StrToJsonArray(str string) ([]interface{}, error)

func StrToMap

func StrToMap(str string) (map[string]interface{}, error)

func String2Int

func String2Int(str string) int

func StringToByteSlice

func StringToByteSlice(s string) []byte

StringToByteSlice []byte only read, panic on append

func StringsContains

func StringsContains(strs []string, str string) bool

func SysError

func SysError(s string)

func SysLog

func SysLog(s string)

func TopupGroupRatio2JSONString

func TopupGroupRatio2JSONString() string

func UnescapeHTML

func UnescapeHTML(x string) interface{}

func Unmarshal

func Unmarshal(data []byte, v any) error

func UnmarshalBodyReusable

func UnmarshalBodyReusable(c *gin.Context, v any) error

func UnmarshalJsonStr

func UnmarshalJsonStr(data string, v any) error

func UpdateTopupGroupRatioByJSONString

func UpdateTopupGroupRatioByJSONString(jsonStr string) error

func ValidateBackupCode

func ValidateBackupCode(code string) bool

ValidateBackupCode 验证备用码格式

func ValidateNumericCode

func ValidateNumericCode(code string) (string, error)

ValidateNumericCode 验证数字验证码格式

func ValidatePasswordAndHash

func ValidatePasswordAndHash(password string, hash string) bool

func ValidateRedirectURL

func ValidateRedirectURL(rawURL string) error

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 ValidateTOTPCode

func ValidateTOTPCode(secret, code string) bool

ValidateTOTPCode 验证TOTP验证码

func ValidateURLWithFetchSetting

func ValidateURLWithFetchSetting(urlStr string, enableSSRFProtection, allowPrivateIp bool, domainFilterMode bool, ipFilterMode bool, domainList, ipList, allowedPorts []string, applyIPFilterForDomain bool) error

ValidateURLWithFetchSetting 使用FetchSetting配置验证URL

func VerifyCodeWithKey

func VerifyCodeWithKey(key string, code string, purpose string) bool

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

type CustomEvent struct {
	Event string
	Id    string
	Retry uint
	Data  interface{}

	Mutex sync.Mutex
}

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 包更新)

func GetDiskCacheConfig

func GetDiskCacheConfig() DiskCacheConfig

GetDiskCacheConfig 获取磁盘缓存配置

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 磁盘缓存统计信息

func GetDiskCacheStats

func GetDiskCacheStats() DiskCacheStats

GetDiskCacheStats 获取缓存统计信息

type EndpointInfo

type EndpointInfo struct {
	Path   string `json:"path"`
	Method string `json:"method"`
}

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)

func (*InMemoryRateLimiter) Request

func (l *InMemoryRateLimiter) Request(key string, maxRequestNum int, duration int64) bool

Request parameter duration's unit is seconds

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 GetPageQuery(c *gin.Context) *PageInfo

func (*PageInfo) GetEndIdx

func (p *PageInfo) GetEndIdx() int

func (*PageInfo) GetPage

func (p *PageInfo) GetPage() int

func (*PageInfo) GetPageSize

func (p *PageInfo) GetPageSize() int

func (*PageInfo) GetStartIdx

func (p *PageInfo) GetStartIdx() int

func (*PageInfo) SetItems

func (p *PageInfo) SetItems(items any)

func (*PageInfo) SetTotal

func (p *PageInfo) SetTotal(total int)

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是否安全

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL