utils

package
v0.0.0-...-f17429d Latest Latest
Warning

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

Go to latest
Published: Apr 26, 2026 License: GPL-3.0 Imports: 62 Imported by: 0

Documentation

Overview

Package jwtauth provides a small HS256 access-token template (claims + sign/parse).

Index

Constants

View Source
const (
	PCONLINE_IP_URL = "http://whois.pconline.com.cn/ipJson.jsp"
	IP_API_URL      = "http://ip-api.com/json/"
	UNKNOWN         = "Unknown"
	INTERNAL_IP     = "内网IP"
	LOCAL_NETWORK   = "Local Network"
)
View Source
const (
	AccessIssuer  = "lingvoice"
	RefreshIssuer = "lingvoice.refresh"
)

Issuers separate access vs refresh JWTs so tokens are not interchangeable.

View Source
const (
	// DefaultTOTPIssuer authenticator apps 显示的发行方名称(otpauth URL)。
	DefaultTOTPIssuer = "LingVoice"
	// DefaultTOTPSecretSize TOTP 密钥字节长度。
	DefaultTOTPSecretSize = 32
	// DefaultTOTPQRPNGSize 二维码 PNG 边长(像素)。
	DefaultTOTPQRPNGSize = 256
)
View Source
const (
	EmailVerificationPurpose = "v"
	PasswordResetPurpose     = "r"
)

Variables

View Source
var DefaultSSRFProtection = &SSRFProtection{
	AllowPrivateIp:   false,
	DomainFilterMode: true,
	DomainList:       []string{},
	IpFilterMode:     true,
	IpList:           []string{},
	AllowedPorts:     []int{},
}

DefaultSSRFProtection 默认SSRF防护配置

View Source
var (
	// ErrInvalidToken is returned when the token is malformed, expired, or signature-invalid.
	ErrInvalidToken = errors.New("jwt: invalid token")
)
View Source
var VerificationValidMinutes = 10

Functions

func CheckValue

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

func ChunkRunes

func ChunkRunes(s string, maxRunes int) []string

ChunkRunes splits s into substrings of at most maxRunes runes (UTF-8 safe).

func CleanupOldDiskCacheFiles

func CleanupOldDiskCacheFiles(maxAge time.Duration) error

CleanupOldDiskCacheFiles 清理旧的缓存文件 maxAge: 文件最大存活时间 注意:此函数只删除文件,不更新统计(因为无法知道每个文件的原始大小)

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 CreateDiskCacheFile

func CreateDiskCacheFile(cacheType DiskCacheType) (string, *os.File, error)

CreateDiskCacheFile 创建磁盘缓存文件 cacheType: 缓存类型(body/file) 返回文件路径和文件句柄

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 EnsureDiskCacheDir

func EnsureDiskCacheDir() error

EnsureDiskCacheDir 确保缓存目录存在

func GenerateQiniuToken

func GenerateQiniuToken(accessKey, secretKey string, req QiniuAuthRequest) (string, error)

GenerateQiniuToken generates a Qiniu authentication token accessKey: Qiniu Access Key secretKey: Qiniu Secret Key req: Authentication request parameters Return: QiniuToken string, in the format of "Qiniu AccessKey:encodedSign"

func GenerateRandomString

func GenerateRandomString(length int) string

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

func GenerateSecureToken

func GenerateSecureToken(length int) (string, error)

GenerateSecureToken generate a fixed-length secure token

func GenerateVerificationCode

func GenerateVerificationCode(length int) string

func GetAudioDuration

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

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

func GetBoolEnv

func GetBoolEnv(key string) bool

func GetBoolValue

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

func GetDBTimestamp

func GetDBTimestamp(db *gorm.DB, driver string) int64

GetDBTimestamp returns a UNIX timestamp from database time. 分布式系统必须用数据库统一时间 如果你的服务部署在多台服务器每台服务器时间可能差几秒~几分钟会导致: 订单时间错乱, 登录日志时间不对, 数据统计异常 Falls back to application time on error.

func GetDiskCacheDir

func GetDiskCacheDir() string

GetDiskCacheDir 获取统一的磁盘缓存目录 注意:每次调用都会重新计算,以响应配置变化

func GetDiskCacheInfo

func GetDiskCacheInfo() (fileCount int, totalSize int64, err error)

GetDiskCacheInfo 获取磁盘缓存目录信息

func GetDiskCacheMaxSizeBytes

func GetDiskCacheMaxSizeBytes() int64

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

func GetDiskCachePath

func GetDiskCachePath() string

GetDiskCachePath 获取磁盘缓存目录

func GetDiskCacheThresholdBytes

func GetDiskCacheThresholdBytes() int64

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

func GetEnv

func GetEnv(key string) string

func GetFloatEnv

func GetFloatEnv(key string) float64

func GetFloatEnvWithDefault

func GetFloatEnvWithDefault(key string, defaultValue float64) float64

GetFloatEnvWithDefault gets float environment variable with default value

func GetIPLocation

func GetIPLocation(ip string) (string, string, string, error)

GetIPLocation 获取 IP 地理位置(自动选择国内/国外接口) 返回:国家、城市、完整地址、错误

func GetIPLocationCN

func GetIPLocationCN(ip string) (string, string, string, error)

GetIPLocationCN 强制使用国内接口查询 IP 地址(更准)

func GetIPLocationGlobal

func GetIPLocationGlobal(ip string) (string, string, string, error)

GetIPLocationGlobal 强制使用国际接口查询 IP 地址

func GetIntEnv

func GetIntEnv(key string) int64

func GetIntEnvWithDefault

func GetIntEnvWithDefault(key string, defaultValue int) int

GetIntEnvWithDefault gets int environment variable with default value

func GetIntValue

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

func GetRealAddressByIP

func GetRealAddressByIP(ip string) string

GetRealAddressByIP 兼容旧接口:只返回地址字符串

func GetSupportedLanguages

func GetSupportedLanguages() []string

GetSupportedLanguages returns list of supported language codes

func GetTimeString

func GetTimeString() string

func GetTimestamp

func GetTimestamp() int64

func GetValue

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

func HTMLToPlainText

func HTMLToPlainText(s string) string

HTMLToPlainText strips tags and style-bearing markup, keeps approximate line breaks, preserves {{.Var}} text.

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 InitDatabase

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

func InitGlobalCache

func InitGlobalCache(maxSize int, expiration time.Duration)

func IsDiskCacheAvailable

func IsDiskCacheAvailable(requestSize int64) bool

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

func IsDiskCacheEnabled

func IsDiskCacheEnabled() bool

IsDiskCacheEnabled 是否启用磁盘缓存

func IsIP

func IsIP(s string) bool

func IsInternalIP

func IsInternalIP(ip string) bool

IsInternalIP 判断是否为内网IP(纯函数)

func IsIpInCIDRList

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

func IsPrivateIP

func IsPrivateIP(ip net.IP) bool

func JoinHTMLBodyAfterTranslation

func JoinHTMLBodyAfterTranslation(prefix, translatedInner, suffix string) string

JoinHTMLBodyAfterTranslation reverses SplitHTMLBodyForTranslation.

func LoadAutoloads

func LoadAutoloads(db *gorm.DB)

func LoadEnv

func LoadEnv(env string) error

LoadEnv loads a single file: `.env`, or `.env.{env}` when env is non-empty (legacy helper).

func LoadEnvs

func LoadEnvs(objPtr any)

load envs to struct

func LoadModuleEnvs

func LoadModuleEnvs(module string, appEnv string) error

LoadModuleEnvs loads layered env files for one deployable binary (auth, server, sip, …):

  1. .env-{module}
  2. .env-{module}.{appEnv} when appEnv is non-empty (overrides earlier keys).

Missing files are skipped with a log line only (same spirit as partial .env loading).

func LookupEnv

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

func MakeMigrates

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

func Monitor

func Monitor()

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

func NormalizeFramePeriod

func NormalizeFramePeriod(d string) time.Duration

ValidateAndNormalizeDuration uses different validation logic with explicit bounds checking

func ParseIP

func ParseIP(s string) net.IP

func RandCredentialAPIKey

func RandCredentialAPIKey() string

RandCredentialAPIKey 生成用户凭证密钥,形如 sk- 前缀 + 随机段,总长 48(与 credential.key char(48) 一致)。

func RandNumberText

func RandNumberText(n int) string

func RandString

func RandString(n int) string

func RandText

func RandText(n int) string

func ReadDiskCacheFile

func ReadDiskCacheFile(filePath string) ([]byte, error)

ReadDiskCacheFile 读取磁盘缓存文件

func ReadDiskCacheFileString

func ReadDiskCacheFileString(filePath string) (string, error)

ReadDiskCacheFileString 读取磁盘缓存文件为字符串

func ReadFile

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

ReadFile read file

func RegisterVerificationCodeWithKey

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

func RemoveDiskCacheFile

func RemoveDiskCacheFile(filePath string) error

RemoveDiskCacheFile 删除磁盘缓存文件

func RemoveEmoji

func RemoveEmoji(text string) string

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

func RemoveEmojiFromJSON

func RemoveEmojiFromJSON(jsonStr string) string

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

func RenderMailHTML

func RenderMailHTML(tplStr string, data map[string]any) (string, error)

RenderMailHTML 使用 html/template 渲染邮件 HTML(占位符与模版中 {{.Key}} 一致,自动转义值)。

func RenderMailText

func RenderMailText(tplStr string, data map[string]any) (string, error)

RenderMailText 使用 text/template 渲染纯文本主题等(占位符 {{.Key}};未传键按 zero 处理)。

func ResetDiskCacheStats

func ResetDiskCacheStats()

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

func ResetDiskCacheUsage

func ResetDiskCacheUsage()

ResetDiskCacheUsage 重置磁盘缓存使用量统计(用于清理缓存后)

func SafeCall

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

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 SetDiskCacheConfig

func SetDiskCacheConfig(config DiskCacheConfig)

SetDiskCacheConfig 设置磁盘缓存配置

func SetPerformanceMonitorConfig

func SetPerformanceMonitorConfig(config PerformanceMonitorConfig)

SetPerformanceMonitorConfig 设置性能监控配置

func SetValue

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

func ShouldUseDiskCache

func ShouldUseDiskCache(dataSize int64) bool

ShouldUseDiskCache 判断是否应该使用磁盘缓存

func SignAccessToken

func SignAccessToken(p AccessPayload, secret string, ttl time.Duration) (string, error)

SignAccessToken issues an HS256 JWT with subject user:<id> and standard time claims.

func SignRefreshToken

func SignRefreshToken(p RefreshPayload, secret string, ttl time.Duration) (string, error)

SignRefreshToken issues a refresh JWT (distinct issuer from access).

func SplitHTMLBodyForTranslation

func SplitHTMLBodyForTranslation(s string) (prefix, inner, suffix string)

SplitHTMLBodyForTranslation splits full HTML into: prefix (through opening <body…>), inner (body children only), suffix (from </body> onward). If there is no <body>…</body> pair, returns prefix="", inner=full, suffix="" so callers may translate the whole fragment.

func StartPyroScope

func StartPyroScope() error

func StartSystemMonitor

func StartSystemMonitor()

StartSystemMonitor 启动系统监控

func StructAsMap

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

func SyncDiskCacheStats

func SyncDiskCacheStats()

SyncDiskCacheStats 从实际磁盘状态同步统计信息 用于修正统计与实际不符的情况

func TOTPKeyToPNGDataURL

func TOTPKeyToPNGDataURL(key *otp.Key, pngSize int) (string, error)

TOTPKeyToPNGDataURL 将已生成的 otp.Key 转为二维码 PNG 的 Data URL(便于 img src 直接使用)。

func TranslateLong

func TranslateLong(t *MyMemoryTranslator, text, from, to string, maxRunes int, pause time.Duration) (string, error)

TranslateLong translates text that may exceed API limits by chunking (rune-based) and concatenating.

func ValidateTOTP

func ValidateTOTP(code, secret string) bool

ValidateTOTP 校验当前时间窗口内的 TOTP 码(前后 trim,空码/空密钥为 false)。

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

func WriteDiskCacheFile

func WriteDiskCacheFile(cacheType DiskCacheType, data []byte) (string, error)

WriteDiskCacheFile 写入数据到磁盘缓存文件 返回文件路径

func WriteDiskCacheFileString

func WriteDiskCacheFileString(cacheType DiskCacheType, data string) (string, error)

WriteDiskCacheFileString 写入字符串到磁盘缓存文件

func WriteFile

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

WriteFile write file

Types

type AccessPayload

type AccessPayload struct {
	UserID uint   `json:"uid"`
	Email  string `json:"email"`
	Role   string `json:"role"`
}

AccessPayload is the application data carried in an access token.

func ParseAccessToken

func ParseAccessToken(tokenString, secret string) (*AccessPayload, error)

ParseAccessToken validates signature and expiry and returns the embedded payload.

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 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 DiskCacheType

type DiskCacheType string

DiskCacheType 磁盘缓存类型

const (
	DiskCacheTypeBody DiskCacheType = "body" // 请求体缓存
	DiskCacheTypeFile DiskCacheType = "file" // 文件数据缓存
)

type DiskSpaceInfo

type DiskSpaceInfo struct {
	// 总空间(字节)
	Total uint64 `json:"total"`
	// 可用空间(字节)
	Free uint64 `json:"free"`
	// 已用空间(字节)
	Used uint64 `json:"used"`
	// 使用百分比
	UsedPercent float64 `json:"used_percent"`
}

DiskSpaceInfo 磁盘空间信息

func GetDiskSpaceInfo

func GetDiskSpaceInfo() DiskSpaceInfo

GetDiskSpaceInfo 获取缓存目录所在磁盘的空间信息 (Unix/Linux/macOS)

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 IPGeolocationResponse

type IPGeolocationResponse struct {
	Country     string  `json:"country"`
	CountryCode string  `json:"countryCode"`
	RegionName  string  `json:"regionName"`
	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 MyMemoryResponse

type MyMemoryResponse struct {
	ResponseData struct {
		TranslatedText string  `json:"translatedText"`
		Match          float64 `json:"match"`
	} `json:"responseData"`
	QuotaFinished   bool   `json:"quotaFinished"`
	MTLangSupported bool   `json:"mtLangSupported"`
	ResponseDetails string `json:"responseDetails"`
	ResponseStatus  int    `json:"responseStatus"`
}

MyMemoryResponse represents the API response

type MyMemoryTranslator

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

MyMemoryTranslator implements Translator using MyMemory Translation API

func NewMyMemoryTranslator

func NewMyMemoryTranslator(email string) *MyMemoryTranslator

NewMyMemoryTranslator creates a new MyMemory translator

func (*MyMemoryTranslator) Translate

func (t *MyMemoryTranslator) Translate(text, from, to string) (string, error)

Translate translates text using MyMemory API

func (*MyMemoryTranslator) TranslateBatch

func (t *MyMemoryTranslator) TranslateBatch(texts []string, from, to string) ([]string, error)

TranslateBatch translates multiple texts

type PerformanceMonitorConfig

type PerformanceMonitorConfig struct {
	Enabled         bool
	CPUThreshold    int
	MemoryThreshold int
	DiskThreshold   int
}

PerformanceMonitorConfig 性能监控配置

func GetPerformanceMonitorConfig

func GetPerformanceMonitorConfig() PerformanceMonitorConfig

GetPerformanceMonitorConfig 获取性能监控配置

type QiniuAuthRequest

type QiniuAuthRequest struct {
	Method      string // HTTP method, supports POST, PUT, GET, must be in all uppercase
	Path        string // Request path
	RawQuery    string // URL query parameters (excluding ?)
	Host        string // Request domain name, for example: atlab.ai
	ContentType string // Request content type, optional
	Body        []byte // Request Body, optional
}

QiniuAuthRequest qiniu authorization request

func BuildQiniuAuthRequest

func BuildQiniuAuthRequest(method, path, host string) *QiniuAuthRequest

BuildQiniuAuthRequest build QiniuAuthRequest

func (*QiniuAuthRequest) SetBody

func (r *QiniuAuthRequest) SetBody(body []byte) *QiniuAuthRequest

SetBody set Body

func (*QiniuAuthRequest) SetBodyString

func (r *QiniuAuthRequest) SetBodyString(bodyStr string) *QiniuAuthRequest

SetBodyString set Body

func (*QiniuAuthRequest) SetContentType

func (r *QiniuAuthRequest) SetContentType(contentType string) *QiniuAuthRequest

SetContentType set ContentType

func (*QiniuAuthRequest) SetRawQuery

func (r *QiniuAuthRequest) SetRawQuery(rawQuery string) *QiniuAuthRequest

SetRawQuery set RawQuery

type RefreshPayload

type RefreshPayload struct {
	UserID uint `json:"uid"`
}

RefreshPayload is embedded in long-lived refresh tokens.

func ParseRefreshToken

func ParseRefreshToken(tokenString, secret string) (*RefreshPayload, error)

ParseRefreshToken validates a refresh JWT.

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 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)

SignalHandler is invoked synchronously for each matching subscription (see Emit), or as part of an async dispatch (see EmitAsync).

type Signals

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

Signals is a pub/sub registry (observer). Emit runs handlers on the caller goroutine; EmitAsync runs a snapshot of handlers on a shared worker pool.

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)

func (*Signals) EmitAsync

func (s *Signals) EmitAsync(ctx context.Context, event string, sender any, params ...any) (*task.Task[asyncEmitPayload, struct{}], error)

EmitAsync schedules a snapshot of current handlers for event on the async worker pool. Handler order matches Emit; subscriptions added after this call are not included.

func (*Signals) SetAsyncPoolFactory

func (s *Signals) SetAsyncPoolFactory(fn func() *task.TaskPool[asyncEmitPayload, struct{}])

SetAsyncPool replaces the default lazy pool factory used by EmitAsync. Pass nil to clear and fall back to the built-in default on next EmitAsync.

type Snowflake

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

func NewSnowflake

func NewSnowflake() (*Snowflake, error)

func (*Snowflake) GenID

func (sf *Snowflake) GenID() string

GenID 字符串格式(正数)

func (*Snowflake) NextID

func (sf *Snowflake) NextID() int64

NextID 生成 唯一 正数 int64

type SystemStatus

type SystemStatus struct {
	CPUUsage    float64
	MemoryUsage float64
	DiskUsage   float64
}

SystemStatus 系统状态信息

func GetSystemStatus

func GetSystemStatus() SystemStatus

GetSystemStatus 获取当前系统状态

type TOTPSetup

type TOTPSetup struct {
	Secret    string // Base32 密钥,可手动录入
	URL       string // otpauth:// 链接
	QRDataURL string // data:image/png;base64,... 便于前端直接展示
}

TOTPSetup 注册双因素认证时返回给客户端的材料。

func GenerateTOTPSetup

func GenerateTOTPSetup(issuer, accountName string, secretSize int) (*TOTPSetup, error)

GenerateTOTPSetup 生成新的 TOTP 密钥、otpauth URL 及二维码 PNG(Data URL)。 issuer 为空时使用 DefaultTOTPIssuer;secretSize <= 0 时使用 DefaultTOTPSecretSize。

Jump to

Keyboard shortcuts

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