utils

package
v0.0.0-...-0409f2c Latest Latest
Warning

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

Go to latest
Published: Dec 29, 2025 License: MIT Imports: 45 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"
)
View Source
const (
	FILE_TYPE_IMAGE int32 = 3
	FILE_TYPE_FILE  int32 = 4
	FILE_TYPE_AUDIO int32 = 5
	FILE_TYPE_MEDIA int32 = 6
)

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 (
	Marshal                                 = json.Marshal
	Unmarshal                               = json.Unmarshal
	MarshalIndent                           = json.MarshalIndent
	NewDecoder    func(r io.Reader) Decoder = useJsonNewDecoder
	NewEncoder    func(w io.Writer) Encoder = useJsonNewEncoder
)
View Source
var EnableDecoderDisallowUnknownFields = false

EnableDecoderDisallowUnknownFields is used to call the DisallowUnknownFields method on the JSON Decoder instance. DisallowUnknownFields causes the Decoder to return an error when the destination is a struct and the input contains object keys which do not match any non-ignored, exported fields in the destination.

View Source
var EnableDecoderUseNumber = false

EnableDecoderUseNumber is used to call the UseNumber method on the JSON Decoder instance. UseNumber causes the Decoder to unmarshal a number into an any as a Number instead of as a float64.

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
View Source
var (
	JsonContentType = []string{"application/json; charset=utf-8"}
)

Functions

func AcquireRegistrationLock

func AcquireRegistrationLock(email string) (bool, error)

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

func AddDuration

func AddDuration(d time.Duration) int64

func AesDecrypt

func AesDecrypt(key, ciphertext []byte) (buf []byte, err error)

func AesEncrypt

func AesEncrypt(key, plaintext []byte) (buf []byte, err error)

func BytesToString

func BytesToString(b []byte) string

BytesToString bytes to string Zero-copy

func CalculateAge

func CalculateAge(birthday time.Time) int

func CalculateFileHash

func CalculateFileHash(filePath string) (string, error)

CalculateFileHash 计算文件的SHA1哈希

func CheckValue

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

func ComputeSampleByteCount

func ComputeSampleByteCount(rate, depth, chans int) int

ComputeSampleByteCount calculates bytes per millisecond for given audio parameters

func ConfigureConnectionPool

func ConfigureConnectionPool(db *gorm.DB)

ConfigureConnectionPool configure database connection pool

func CopyFile

func CopyFile(src, dst string) error

CopyFile 复制文件

func Difference

func Difference[T comparable](slice1, slice2 []T) []T

Difference get difference set slice1-intersection

func EndOfDay

func EndOfDay(t time.Time) time.Time

func EnsureDirectory

func EnsureDirectory(path string) error

EnsureDirectory 确保目录存在

func ExtractKeyFromURL

func ExtractKeyFromURL(url string) string

ExtractKeyFromURL 从URL中提取文件路径

func FileExists

func FileExists(path string) bool

FileExists 检查文件是否存在

func GenerateID

func GenerateID() string

GenerateID 生成唯一的ID

func GenerateRandomString

func GenerateRandomString(length int) string

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

func GenerateSecureToken

func GenerateSecureToken(length int) (string, error)

GenerateSecureToken generate a fixed-length secure token

func GetBoolEnv

func GetBoolEnv(key string) bool

func GetBoolValue

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

func GetContentType

func GetContentType(suffix string) (tp string)

func GetCrc16

func GetCrc16(val int64) uint16

func GetDeviceID

func GetDeviceID(userAgent, ipAddress string) string

GetDeviceID 从User-Agent生成设备ID

func GetDistance

func GetDistance(lon1, lat1, lon2, lat2 float64) float64

Calculate distance between two points

func GetEnv

func GetEnv(key string) string

func GetFileExtension

func GetFileExtension(filename string) string

GetFileExtension 获取文件扩展名

func GetFileSize

func GetFileSize(filePath string) (int64, error)

GetFileSize 获取文件大小

func GetFileType

func GetFileType(buf []byte) (fileType string)

func GetFileTypeBySuffix

func GetFileTypeBySuffix(suffix string) int32

func GetFloatEnv

func GetFloatEnv(key string) float64

func GetIPLocation

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

GetIPLocation 获取IP地理位置(使用全局服务实例)

func GetIntEnv

func GetIntEnv(key string) int64

func GetIntValue

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

func GetRealAddressByIP

func GetRealAddressByIP(ip string) string

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

func GetValue

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

func InArray

func InArray[T comparable](needle T, haystack []T) bool

InArray check if element is in array

func InitConfigManager

func InitConfigManager(cacheInstance cache.Cache)

InitConfigManager 初始化配置管理器

func InitDatabase

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

func InitGlobalDistributedLock

func InitGlobalDistributedLock()

InitGlobalDistributedLock 初始化全局分布式锁

func InitGlobalIPLocationService

func InitGlobalIPLocationService(logger *zap.Logger)

InitGlobalIPLocationService 初始化全局IP地理位置服务

func InitGlobalLoginSecurityManager

func InitGlobalLoginSecurityManager(logger *zap.Logger, cacheInstance cache.Cache)

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

func InitGlobalRegistrationGuard

func InitGlobalRegistrationGuard(logger *zap.Logger, cacheInstance cache.Cache)

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

func Intersect

func Intersect[T comparable](slice1, slice2 []T) []T

Intersect get intersection

func IsDirectory

func IsDirectory(path string) bool

IsDirectory 检查路径是否为目录

func IsFile

func IsFile(path string) bool

IsFile 检查路径是否为文件

func IsInternalIP

func IsInternalIP(ip string) bool

IsInternalIP 判断是否为内网IP

func Join

func Join[T any](arg []T, str string) string

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 MD5

func MD5(str string) string

func MakeMigrates

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

func Merge

func Merge[T any](slice1, slice2 []T) []T

Merge get union

func MillisFromTime

func MillisFromTime(t time.Time) int64

func NormalizeFramePeriod

func NormalizeFramePeriod(d string) time.Duration

ValidateAndNormalizeDuration uses different validation logic with explicit bounds checking

func NowUnix

func NowUnix() int64

func ParseUserAgent

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

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

func RC4Decrypt

func RC4Decrypt(str string, key []byte) string

func RC4Encrypt

func RC4Encrypt(str string, key []byte) string

func RandNumberText

func RandNumberText(n int) string

func RandString

func RandString(n int) string

func RandText

func RandText(n int) string

func ReadFile

func ReadFile(filename string) ([]byte, error)

ReadFile read file

func ReleaseRegistrationLock

func ReleaseRegistrationLock(email string) error

ReleaseRegistrationLock 释放注册锁

func RemoveDirectory

func RemoveDirectory(path string) error

RemoveDirectory 删除目录

func RemoveEmoji

func RemoveEmoji(text string) string

removeEmoji 移除字符串中的 emoji 字符,避免数据库字符集不兼容问题

func RemoveEmojiFromJSON

func RemoveEmojiFromJSON(jsonStr string) string

removeEmojiFromJSON 从 JSON 字符串中移除 emoji(仅从字符串值中移除,保持 JSON 结构)

func RemoveFile

func RemoveFile(path string) error

RemoveFile 删除文件

func RenderJSON

func RenderJSON(c *gin.Context, code int, obj any)

func SafeCall

func SafeCall(f func() error, failHandle func(error)) error

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 SanitizeValue

func SanitizeValue(value interface{}) interface{}

SanitizeValue sanitize value to prevent injection

func SetValue

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

func SixteenMD5

func SixteenMD5(str string) string

func StartOfDay

func StartOfDay(t time.Time) time.Time

func StringToBytes

func StringToBytes(s string) []byte

StringToBytes string to bytes Zero-copy

func StructAsMap

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

func TimeFromMillis

func TimeFromMillis(millis int64) time.Time

func UnZlib

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

func Unique

func Unique[T comparable](slice []T) []T

Unique remove duplicates from array

func ValidateDisplayName

func ValidateDisplayName(name string) error

ValidateDisplayName 验证显示名称

func ValidateEmailFormat

func ValidateEmailFormat(email string) error

ValidateEmailFormat 验证邮箱格式

func ValidateInput

func ValidateInput(input interface{}) error

ValidateInput validate input parameters

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 WriteFile

func WriteFile(filename string, data []byte) error

WriteFile write file

func WriteJSON

func WriteJSON(w http.ResponseWriter, obj any) error

WriteJSON marshals the given interface object and writes it with custom ContentType.

func Yesterday

func Yesterday() time.Time

func Zlib

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

Types

type AccountLockInfo

type AccountLockInfo struct {
	IsLocked bool
	UnlockAt time.Time
}

AccountLockInfo 账号锁定信息

type CarrotJSON

type CarrotJSON struct {
	Data any
}

func (CarrotJSON) Render

func (r CarrotJSON) Render(w http.ResponseWriter) error

Render (JSON) writes data with custom ContentType.

func (CarrotJSON) WriteContentType

func (r CarrotJSON) WriteContentType(w http.ResponseWriter)

WriteContentType (JSON) writes JSON ContentType.

type CarrotJsonBinding

type CarrotJsonBinding struct{}

func (CarrotJsonBinding) Bind

func (CarrotJsonBinding) Bind(req *http.Request, obj any) error

func (CarrotJsonBinding) BindBody

func (CarrotJsonBinding) BindBody(body []byte, obj any) error

func (CarrotJsonBinding) Name

func (CarrotJsonBinding) Name() string

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 ConfigManager

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

ConfigManager 配置管理器

type Decoder

type Decoder interface {
	Decode(v any) error
}

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 Encoder

type Encoder interface {
	Encode(v any) error
}

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 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地理位置服务

var GlobalIPLocationService *IPLocationService

GlobalIPLocationService 全局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 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, cacheInstance cache.Cache) *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 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, cacheInstance cache.Cache) *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 SecureQueryBuilder

type SecureQueryBuilder struct {
	Db *gorm.DB
}

SecureQueryBuilder secure query builder

func NewSecureQueryBuilder

func NewSecureQueryBuilder(db *gorm.DB) *SecureQueryBuilder

NewSecureQueryBuilder create a secure query builder

func (*SecureQueryBuilder) SafeCount

func (sqb *SecureQueryBuilder) SafeCount(model interface{}) (int64, error)

SafeCount secure count query

func (*SecureQueryBuilder) SafeExists

func (sqb *SecureQueryBuilder) SafeExists(model interface{}, conditions map[string]interface{}) (bool, error)

SafeExists secure existence check

func (*SecureQueryBuilder) SafeFind

func (sqb *SecureQueryBuilder) SafeFind(dest interface{}, conditions map[string]interface{}) error

SafeFind secure batch query

func (*SecureQueryBuilder) SafeFirst

func (sqb *SecureQueryBuilder) SafeFirst(dest interface{}, conditions map[string]interface{}) error

SafeFirst secure first record query

func (*SecureQueryBuilder) SafeGroup

func (sqb *SecureQueryBuilder) SafeGroup(columns []string) *gorm.DB

SafeGroup secure GROUP BY builder

func (*SecureQueryBuilder) SafeHaving

func (sqb *SecureQueryBuilder) SafeHaving(condition string, args ...interface{}) *gorm.DB

SafeHaving secure HAVING condition builder

func (*SecureQueryBuilder) SafeOrder

func (sqb *SecureQueryBuilder) SafeOrder(column string, direction string) *gorm.DB

SafeOrder secure ORDER BY builder

func (*SecureQueryBuilder) SafePaginate

func (sqb *SecureQueryBuilder) SafePaginate(page, pageSize int) *gorm.DB

SafePaginate secure pagination query

func (*SecureQueryBuilder) SafeQuery

func (sqb *SecureQueryBuilder) SafeQuery(query string, args ...interface{}) *gorm.DB

SafeQuery execute secure raw query

func (*SecureQueryBuilder) SafeSelect

func (sqb *SecureQueryBuilder) SafeSelect(columns []string) *gorm.DB

SafeSelect secure SELECT field builder

func (*SecureQueryBuilder) SafeTransaction

func (sqb *SecureQueryBuilder) SafeTransaction(fn func(*gorm.DB) error) error

SafeTransaction execute secure transaction

func (*SecureQueryBuilder) SafeWhere

func (sqb *SecureQueryBuilder) SafeWhere(column string, operator string, value interface{}) *gorm.DB

SafeWhere secure WHERE condition builder

type Session

type Session struct {
	// Session ID
	ID string

	// Creation time
	CreatedAt time.Time

	// Last activity time
	LastActivity time.Time

	// Session data
	Data map[string]interface{}
	// contains filtered or unexported fields
}

Session represents a server-side session

func NewSession

func NewSession() *Session

NewSession creates a new session

func (*Session) GetCreatedAt

func (s *Session) GetCreatedAt() time.Time

GetCreatedAt returns the session creation time

func (*Session) GetData

func (s *Session) GetData(key string) (interface{}, bool)

GetData retrieves session data

func (*Session) GetID

func (s *Session) GetID() string

GetID returns the session ID

func (*Session) GetLastActivity

func (s *Session) GetLastActivity() time.Time

GetLastActivity returns the last activity time

func (*Session) SetData

func (s *Session) SetData(key string, value interface{})

SetData sets session data

func (*Session) UpdateActivity

func (s *Session) UpdateActivity()

UpdateActivity updates the last activity time

type SessionManager

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

SessionManager manages server-side sessions

func NewSessionManager

func NewSessionManager(expirySeconds int) *SessionManager

NewSessionManager creates a session manager

func (*SessionManager) CreateSession

func (m *SessionManager) CreateSession() *Session

CreateSession creates a new session

func (*SessionManager) GetActiveSessions

func (m *SessionManager) GetActiveSessions() []string

GetActiveSessions retrieves all active session IDs

func (*SessionManager) GetSession

func (m *SessionManager) GetSession(id string) (*Session, bool)

GetSession retrieves a session

func (*SessionManager) TerminateSession

func (m *SessionManager) TerminateSession(id string) bool

TerminateSession terminates a session

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

Jump to

Keyboard shortcuts

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