utils

package
v0.0.0-...-5c91321 Latest Latest
Warning

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

Go to latest
Published: Feb 27, 2026 License: MIT Imports: 40 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// IP地址查询API(国内)
	PCONLINE_IP_URL = "http://whois.pconline.com.cn/ipJson.jsp"

	// IP地址查询API(国际)
	IP_API_URL = "http://ip-api.com/json/"

	// 未知地址
	UNKNOWN = "Unknown"

	// 内网IP标识
	INTERNAL_IP   = "内网IP"
	LOCAL_NETWORK = "Local Network"
)

Variables

View Source
var (
	// Tools related errors
	ErrInvalidToolListFormat = errors.New("invalid tool list response format")
	ErrInvalidToolFormat     = errors.New("invalid tool format")
	ErrToolNotFound          = errors.New("tool not found")
	ErrInvalidToolParams     = errors.New("invalid tool parameters")

	// JSON-RPC related errors
	ErrParseJSONRPC           = errors.New("failed to parse JSON-RPC message")
	ErrInvalidJSONRPCFormat   = errors.New("invalid JSON-RPC format")
	ErrInvalidJSONRPCResponse = errors.New("invalid JSON-RPC response")
	ErrInvalidJSONRPCRequest  = errors.New("invalid JSON-RPC request")
	ErrInvalidJSONRPCParams   = errors.New("invalid JSON-RPC parameters")

	// Resource related errors
	ErrInvalidResourceFormat = errors.New("invalid resource format")
	ErrResourceNotFound      = errors.New("resource not found")

	// Prompt related errors
	ErrInvalidPromptFormat = errors.New("invalid prompt format")
	ErrPromptNotFound      = errors.New("prompt not found")

	// Tool manager errors
	ErrEmptyToolName         = errors.New("tool name cannot be empty")
	ErrToolAlreadyRegistered = errors.New("tool already registered")
	ErrToolExecutionFailed   = errors.New("tool execution failed")

	// Resource manager errors
	ErrEmptyResourceURI = errors.New("resource URI cannot be empty")

	// Prompt manager errors
	ErrEmptyPromptName = errors.New("prompt name cannot be empty")

	// Lifecycle manager errors
	ErrSessionAlreadyInitialized = errors.New("session already initialized")
	ErrSessionNotInitialized     = errors.New("session not initialized")

	// Parameter errors
	ErrInvalidParams = errors.New("invalid parameters")
	ErrMissingParams = errors.New("missing required parameters")

	// Client errors
	ErrAlreadyInitialized = errors.New("client already initialized")
	ErrNotInitialized     = errors.New("client not initialized")
	ErrInvalidServerURL   = errors.New("invalid server URL")
)

Common errors

View Source
var ErrAttachmentNotExist = &Error{Code: http.StatusNotFound, Message: "attachment not exist"}
View Source
var ErrBadToken = errors.New("bad token") // Token has been tampered with, forged or is invalid
View Source
var ErrEmailExists = errors.New("email exists, please use another email") // Email already exists, trying to register or update to an already registered email
View Source
var ErrEmailRequired = errors.New("email required") // Email field must be provided but was not provided
View Source
var ErrEmptyEmail = errors.New("empty email") // Email is empty, typically used for registration, login, password recovery and other operations
View Source
var ErrEmptyPassword = errors.New("empty password") // Password is empty, typically used for registration or login validation failure
View Source
var ErrForbidden = errors.New("forbidden access") // Access denied, user is logged in but has no permission to access the target resource
View Source
var ErrInvalidPrimaryKey = errors.New("invalid primary key") // Primary key is invalid, possibly due to format error or missing
View Source
var ErrInvalidToken = errors.New("invalid token") // Token format is illegal or does not conform to specifications
View Source
var ErrInvalidView = errors.New("with invalid view") // Request used an invalid view identifier or parameter
View Source
var ErrLLMCallFailed = errors.New("failed to call language model") // Failed to call language model
View Source
var ErrNotActivated = errors.New("user not activated") // User account is not activated, usually used when email activation is not completed
View Source
var ErrNotAttachmentOwner = &Error{Code: http.StatusForbidden, Message: "not attachment owner"}
View Source
var ErrNotChanged = errors.New("not changed") // Data has not changed, for example no actual field changes in update request
View Source
var ErrNotFound = errors.New("not found") // Requested data or resource not found
View Source
var ErrOnlySuperUser = errors.New("only super user can do this") // Operations limited to super users only
View Source
var ErrQuotaExceeded = errors.New("quota exceeded") // User quota has been exhausted
View Source
var ErrSameEmail = errors.New("same email") // Old and new email are the same, triggered when user tries to change email
View Source
var ErrTokenExpired = errors.New("token expired") // Token has expired
View Source
var ErrTokenRequired = errors.New("token required") // Missing required token, for example when accessing protected resources
View Source
var ErrUnauthorized = &Error{Code: http.StatusUnauthorized, Message: "unauthorized"}
View Source
var ErrUserNotAllowLogin = errors.New("user not allow login") // User is prohibited from logging in, possibly banned by administrator
View Source
var ErrUserNotAllowSignup = errors.New("user not allow signup") // User is prohibited from registering, system configuration or policy restricts registration behavior
View Source
var ErrUserNotExists = errors.New("user not exists") // User does not exist, commonly used for login, query or operations on non-existent users

Functions

func AcquireRegistrationLock

func AcquireRegistrationLock(email string) (bool, error)

AcquireRegistrationLock 获取注册锁(防止并发注册同一邮箱)

func CheckValue

func CheckValue(db *gorm.DB, key, defaultValue, format string, autoload, public bool)

func ConfigureConnectionPool

func ConfigureConnectionPool(db *gorm.DB)

ConfigureConnectionPool configure database connection pool

func ExtractKeyFromURL

func ExtractKeyFromURL(url string) string

ExtractKeyFromURL 从URL中提取文件路径

func FileExists

func FileExists(path string) bool

FileExists 在 utils 包中添加

func GenerateDefaultSessionSecret

func GenerateDefaultSessionSecret() string

GenerateDefaultSessionSecret 生成默认的会话密钥(仅用于开发环境)

func GenerateRandomString

func GenerateRandomString(length int) string

GenerateRandomString 生成指定长度的随机字符串

func GetBoolEnv

func GetBoolEnv(key string) bool

func GetBoolOrDefault

func GetBoolOrDefault(key string, defaultValue bool) bool

GetBoolOrDefault 获取布尔环境变量值,如果为空则返回默认值

func GetBoolValue

func GetBoolValue(db *gorm.DB, key string) bool

func GetDeviceID

func GetDeviceID(userAgent, ipAddress string) string

GetDeviceID 从User-Agent生成设备ID

func GetEnv

func GetEnv(key string) string

func GetFileExtension

func GetFileExtension(filename string) string

GetFileExtension 获取文件扩展名

func GetFloatEnv

func GetFloatEnv(key string) float64

func GetIPLocation

func GetIPLocation(ip string) (country, city, location string, err error)

func GetInt64OrDefault

func GetInt64OrDefault(key string, defaultValue int64) int64

GetInt64OrDefault 获取整数环境变量值,如果为空则返回默认值

func GetIntEnv

func GetIntEnv(key string) int64

func GetIntOrDefault

func GetIntOrDefault(key string, defaultValue int) int

GetIntOrDefault 获取整数环境变量值,如果为空则返回默认值

func GetIntValue

func GetIntValue(db *gorm.DB, key string, defaultVal int) int

func GetRealAddressByIP

func GetRealAddressByIP(ip string) string

GetRealAddressByIP 根据IP获取真实地址(兼容旧接口,返回完整地址字符串)

func GetStringOrDefault

func GetStringOrDefault(key, defaultValue string) string

GetStringOrDefault 获取环境变量值,如果为空则返回默认值

func GetValue

func GetValue(db *gorm.DB, key string) string

func InitDatabase

func InitDatabase(logWrite io.Writer, driver, dsn string) (*gorm.DB, error)

func InitGlobalCache

func InitGlobalCache(maxSize int, expiration time.Duration)

func InitGlobalDistributedLock

func InitGlobalDistributedLock()

InitGlobalDistributedLock 初始化全局分布式锁

func InitGlobalLoginSecurityManager

func InitGlobalLoginSecurityManager(logger *zap.Logger)

InitGlobalLoginSecurityManager 初始化全局登录安全管理器

func InitGlobalRegistrationGuard

func InitGlobalRegistrationGuard(logger *zap.Logger)

InitGlobalRegistrationGuard 初始化全局注册防护服务

func IsInternalIP

func IsInternalIP(ip string) bool

IsInternalIP 判断是否为内网IP

func LoadAutoloads

func LoadAutoloads(db *gorm.DB)

func LoadEnv

func LoadEnv(env string) error

LoadEnv Load .env file based on environment

func LoadEnvs

func LoadEnvs(objPtr any)

load envs to struct

func LookupEnv

func LookupEnv(key string) (value string, found bool)

func MakeMigrates

func MakeMigrates(db *gorm.DB, insts []any) error

func ParseUserAgent

func ParseUserAgent(userAgent string) (deviceType, os, browser string)

ParseUserAgent 解析User-Agent获取设备信息

func RandNumberText

func RandNumberText(n int) string

func RandString

func RandString(n int) string

func RandText

func RandText(n int) string

func ReleaseRegistrationLock

func ReleaseRegistrationLock(email string) error

ReleaseRegistrationLock 释放注册锁

func SanitizeAndValidate

func SanitizeAndValidate(input string, inputType string) (string, error)

SanitizeAndValidate 清理并验证输入

func SanitizeEmail

func SanitizeEmail(email string) string

SanitizeEmail 清理邮箱地址

func SanitizeInput

func SanitizeInput(input string) string

SanitizeInput 清理输入,去除首尾空格和特殊字符

func SanitizePassword

func SanitizePassword(password string) string

SanitizePassword 清理密码(保留空格,但去除首尾空格)

func SetValue

func SetValue(db *gorm.DB, key, value, format string, autoload, public bool)

func StructAsMap

func StructAsMap(form any, fields []string) (vals map[string]any)

func UnZlib

func UnZlib(in []byte) (out []byte)

func ValidateDisplayName

func ValidateDisplayName(name string) error

ValidateDisplayName 验证显示名称

func ValidateEmailFormat

func ValidateEmailFormat(email string) error

ValidateEmailFormat 验证邮箱格式

func ValidatePasswordFormat

func ValidatePasswordFormat(password string) error

ValidatePasswordFormat 验证密码格式

func ValidateSQLInjection

func ValidateSQLInjection(input string) error

ValidateSQLInjection 检查SQL注入风险

func ValidateUserName

func ValidateUserName(username string) error

ValidateUserName 验证用户名

func ValidateXSS

func ValidateXSS(input string) error

ValidateXSS 检查XSS攻击风险

func Zlib

func Zlib(in []byte) (out []byte)

Types

type AVProbeOutput

type AVProbeOutput struct {
	Streams []map[string]any `json:"streams"`
	Format  map[string]any   `json:"format"`
}

AVProbeOutput 为 ffprobe -print_format json 的核心输出结构 这里使用 map 保留所有字段(你示例里的 streams/format/tags/disposition 等都能透传)

type AccountLockInfo

type AccountLockInfo struct {
	IsLocked bool
	UnlockAt time.Time
}

AccountLockInfo 账号锁定信息

type CheckAccountLockFunc

type CheckAccountLockFunc func(*gorm.DB, string, uint) (*AccountLockInfo, error)

CheckAccountLockFunc 检查账号锁定的函数类型

type CheckPasswordLoginLimitFunc

type CheckPasswordLoginLimitFunc func(*gorm.DB, uint) (int64, error)

CheckPasswordLoginLimitFunc 检查密码登录次数限制的函数类型

type Config

type Config struct {
	ID        uint   `json:"id" gorm:"primaryKey"`
	Key       string `json:"key" gorm:"size:128;uniqueIndex"`
	Desc      string `json:"desc" gorm:"size:200"`
	Autoload  bool   `json:"autoload" gorm:"index"`
	Public    bool   `json:"public" gorm:"index" default:"false"`
	Format    string `json:"format" gorm:"size:20" default:"text" comment:"json,yaml,int,float,bool,text"`
	Value     string
	CreatedAt time.Time `json:"-" gorm:"autoCreateTime"`
	UpdatedAt time.Time `json:"-" gorm:"autoUpdateTime"`
}

func LoadPublicConfigs

func LoadPublicConfigs(db *gorm.DB) []Config

type DistributedLock

type DistributedLock interface {
	Lock(key string, ttl time.Duration) (bool, error)
	Unlock(key string) error
	TryLock(key string, ttl time.Duration) (bool, error)
}

DistributedLock 分布式锁接口

var GlobalDistributedLock DistributedLock

GlobalDistributedLock 全局分布式锁实例

type Error

type Error struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
}

func (Error) Error

func (e Error) Error() string

func (Error) StatusCode

func (e Error) StatusCode() int

type ExpiredLRUCache

type ExpiredLRUCache[K comparable, V any] struct {
	*lru.Cache[K, expiredLRUCacheValue[V]]
	// contains filtered or unexported fields
}
var GlobalCache *ExpiredLRUCache[string, any]

GlobalCache is a global cache instance that supports generic key-value pairs

func NewExpiredLRUCache

func NewExpiredLRUCache[K comparable, V any](size int, expired time.Duration) *ExpiredLRUCache[K, V]

func (*ExpiredLRUCache[K, V]) Add

func (c *ExpiredLRUCache[K, V]) Add(key K, value V) (evicted bool)

func (*ExpiredLRUCache[K, V]) Contains

func (c *ExpiredLRUCache[K, V]) Contains(key K) bool

func (*ExpiredLRUCache[K, V]) Get

func (c *ExpiredLRUCache[K, V]) Get(key K) (value V, ok bool)

func (*ExpiredLRUCache[K, V]) Remove

func (c *ExpiredLRUCache[K, V]) Remove(key K) (present bool)

type FileMetadata

type FileMetadata struct {
	FilePath      string         `json:"filePath"`
	FileName      string         `json:"fileName"`
	FileExtension string         `json:"fileExtension,omitempty"`
	Size          int64          `json:"size"`
	ModTime       int64          `json:"modTime"` // Unix timestamp
	MimeType      string         `json:"mimeType,omitempty"`
	Kind          string         `json:"kind,omitempty"` // image / video / audio / other
	Image         *ImageInfo     `json:"image,omitempty"`
	AV            *AVProbeOutput `json:"av,omitempty"`
}

FileMetadata 为统一元数据输出(基础信息 + 可选 image/av)

type GetRecentLoginLocationsFunc

type GetRecentLoginLocationsFunc func(*gorm.DB, uint, int) ([]LoginLocation, error)

GetRecentLoginLocationsFunc 获取最近登录位置的函数类型

type IPGeolocationResponse

type IPGeolocationResponse struct {
	Country     string  `json:"country"`
	CountryCode string  `json:"countryCode"`
	Region      string  `json:"region"`
	City        string  `json:"city"`
	Lat         float64 `json:"lat"`
	Lon         float64 `json:"lon"`
	Timezone    string  `json:"timezone"`
	ISP         string  `json:"isp"`
	Org         string  `json:"org"`
	AS          string  `json:"as"`
	Query       string  `json:"query"`
	Status      string  `json:"status"`
	Message     string  `json:"message"`
}

IPGeolocationResponse IP地理位置API响应(ip-api格式)

type IPLocationResponse

type IPLocationResponse struct {
	Pro  string `json:"pro"`  // 省份
	City string `json:"city"` // 城市
}

IPLocationResponse IP地理位置查询响应结构(pconline格式)

type IPLocationService

type IPLocationService struct {
	// contains filtered or unexported fields
}

IPLocationService IP地理位置服务

func NewIPLocationService

func NewIPLocationService(logger *zap.Logger) *IPLocationService

NewIPLocationService 创建IP地理位置服务

func NewIPLocationServiceWithPconline

func NewIPLocationServiceWithPconline(logger *zap.Logger) *IPLocationService

NewIPLocationServiceWithPconline 创建使用pconline API的IP地理位置服务(国内IP更准确)

func (*IPLocationService) GetLocation

func (ils *IPLocationService) GetLocation(ip string) (country, city, location string, err error)

GetLocation 获取IP地理位置(返回国家、城市、完整位置字符串)

type ImageInfo

type ImageInfo struct {
	Width           int    `json:"width"`
	Height          int    `json:"height"`
	Format          string `json:"format"`
	ColorModel      string `json:"colorModel"`
	BitsPerPixel    int    `json:"bitsPerPixel,omitempty"`
	Channels        int    `json:"channels,omitempty"`
	HasTransparency bool   `json:"hasTransparency,omitempty"`
}

ImageInfo 表示图片元数据(仅图片维度)

type LoginLocation

type LoginLocation struct {
	Country string
	City    string
}

LoginLocation 登录位置信息

type LoginSecurityManager

type LoginSecurityManager struct {
	// contains filtered or unexported fields
}

LoginSecurityManager 登录安全管理器

var GlobalLoginSecurityManager *LoginSecurityManager

GlobalLoginSecurityManager 全局登录安全管理器

func NewLoginSecurityManager

func NewLoginSecurityManager(logger *zap.Logger) *LoginSecurityManager

NewLoginSecurityManager 创建登录安全管理器

func (*LoginSecurityManager) CheckAccountLock

func (lsm *LoginSecurityManager) CheckAccountLock(db *gorm.DB, email string, userID uint, checkFunc CheckAccountLockFunc) error

CheckAccountLock 检查账号是否被锁定

func (*LoginSecurityManager) CheckIPRateLimit

func (lsm *LoginSecurityManager) CheckIPRateLimit(ip string) error

CheckIPRateLimit 检查IP登录限流

func (*LoginSecurityManager) CheckPasswordLoginLimit

func (lsm *LoginSecurityManager) CheckPasswordLoginLimit(db *gorm.DB, userID uint, email string, checkFunc CheckPasswordLoginLimitFunc) (bool, error)

CheckPasswordLoginLimit 检查密码登录次数限制

func (*LoginSecurityManager) CheckProxyIP

func (lsm *LoginSecurityManager) CheckProxyIP(ip string) (bool, error)

CheckProxyIP 检查是否为代理IP(简单检测)

func (*LoginSecurityManager) ClearFailedLoginCount

func (lsm *LoginSecurityManager) ClearFailedLoginCount(email string)

ClearFailedLoginCount 清除失败登录计数(登录成功时调用)

func (*LoginSecurityManager) DetectSuspiciousLogin

func (lsm *LoginSecurityManager) DetectSuspiciousLogin(db *gorm.DB, userID uint, currentIP, currentLocation, currentCountry string, getLocationsFunc GetRecentLoginLocationsFunc) (bool, error)

DetectSuspiciousLogin 检测可疑登录(异地登录)

func (*LoginSecurityManager) RecordFailedLogin

func (lsm *LoginSecurityManager) RecordFailedLogin(db *gorm.DB, email string, userID uint, ipAddress string, recordFunc RecordFailedLoginFunc) error

RecordFailedLogin 记录失败登录

type MemoryLock

type MemoryLock struct {
	// contains filtered or unexported fields
}

MemoryLock 内存锁实现(单机版)

func NewMemoryLock

func NewMemoryLock() *MemoryLock

NewMemoryLock 创建内存锁

func (*MemoryLock) Lock

func (ml *MemoryLock) Lock(key string, ttl time.Duration) (bool, error)

Lock 获取锁

func (*MemoryLock) TryLock

func (ml *MemoryLock) TryLock(key string, ttl time.Duration) (bool, error)

TryLock 尝试获取锁(非阻塞)

func (*MemoryLock) Unlock

func (ml *MemoryLock) Unlock(key string) error

Unlock 释放锁

type MetadataService

type MetadataService interface {
	// GetFileMetadata 返回统一元数据(会自动尝试识别图片信息;不自动跑 ffprobe)
	GetFileMetadata(filePath string) (*FileMetadata, error)
	// GetAVMetadata 通过 ffprobe 获取音视频元数据(用于 ?avinfo=true)
	GetAVMetadata(filePath string) (*AVProbeOutput, error)
}

MetadataService 定义元数据解析服务接口

func NewMetadataService

func NewMetadataService() MetadataService

NewMetadataService 创建新的元数据解析服务实例

type RecordFailedLoginFunc

type RecordFailedLoginFunc func(*gorm.DB, string, uint, string, int) error

RecordFailedLoginFunc 记录失败登录的函数类型

type RegistrationAttempt

type RegistrationAttempt struct {
	IP        string
	Email     string
	Timestamp time.Time
	Success   bool
	Reason    string
}

RegistrationAttempt 注册尝试记录

type RegistrationGuard

type RegistrationGuard struct {
	// contains filtered or unexported fields
}

RegistrationGuard 注册防护服务

var GlobalRegistrationGuard *RegistrationGuard

GlobalRegistrationGuard 全局注册防护服务实例

func NewRegistrationGuard

func NewRegistrationGuard(logger *zap.Logger) *RegistrationGuard

NewRegistrationGuard 创建注册防护服务实例

func (*RegistrationGuard) AddIPToBlacklist

func (rg *RegistrationGuard) AddIPToBlacklist(cidr string) error

AddIPToBlacklist 动态添加IP到黑名单

func (*RegistrationGuard) CheckFailedAttempts

func (rg *RegistrationGuard) CheckFailedAttempts(ip string) error

CheckFailedAttempts 检查失败尝试次数

func (*RegistrationGuard) CheckIPRateLimit

func (rg *RegistrationGuard) CheckIPRateLimit(ip string) error

CheckIPRateLimit 检查IP注册限流

func (*RegistrationGuard) CheckRegistrationAllowed

func (rg *RegistrationGuard) CheckRegistrationAllowed(ip string, email string, password string) error

CheckRegistrationAllowed 综合检查是否允许注册

func (*RegistrationGuard) RecordRegistrationAttempt

func (rg *RegistrationGuard) RecordRegistrationAttempt(ip string, email string, success bool, reason string)

RecordRegistrationAttempt 记录注册尝试

func (*RegistrationGuard) ValidateEmail

func (rg *RegistrationGuard) ValidateEmail(email string) error

ValidateEmail 验证邮箱格式和域名

func (*RegistrationGuard) ValidateIP

func (rg *RegistrationGuard) ValidateIP(ip string) error

ValidateIP 验证IP地址是否在黑名单中

func (*RegistrationGuard) ValidatePassword

func (rg *RegistrationGuard) ValidatePassword(password string) error

ValidatePassword 验证密码强度

type SigHandler

type SigHandler struct {
	ID      uint
	Handler SignalHandler
}

type SigHandlerEvent

type SigHandlerEvent struct {
	EvType     int
	SignalName string
	SigHandler SigHandler
}

type SignalHandler

type SignalHandler func(sender any, params ...any)

Signals

type Signals

type Signals struct {
	// contains filtered or unexported fields
}

func NewSignals

func NewSignals() *Signals

func Sig

func Sig() *Signals

func (*Signals) Clear

func (s *Signals) Clear(events ...string)

func (*Signals) Connect

func (s *Signals) Connect(event string, handler SignalHandler) uint

func (*Signals) Disconnect

func (s *Signals) Disconnect(event string, id uint)

func (*Signals) Emit

func (s *Signals) Emit(event string, sender any, params ...any)

type Snowflake

type Snowflake struct {
	// contains filtered or unexported fields
}
var SnowflakeUtil *Snowflake

func NewSnowflake

func NewSnowflake() (*Snowflake, error)

func (*Snowflake) NextID

func (s *Snowflake) NextID() int64

Directories

Path Synopsis
qiniu

Jump to

Keyboard shortcuts

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