Documentation
¶
Overview ¶
Package jwtauth provides a small HS256 access-token template (claims + sign/parse).
Index ¶
- Constants
- Variables
- func CheckValue(db *gorm.DB, key, defaultValue, format string, autoload, public bool)
- func ChunkRunes(s string, maxRunes int) []string
- func CleanupOldDiskCacheFiles(maxAge time.Duration) error
- func ComputeSampleByteCount(rate, depth, chans int) int
- func ConfigureConnectionPool(db *gorm.DB)
- func CreateDiskCacheFile(cacheType DiskCacheType) (string, *os.File, error)
- func DecrementDiskFiles(size int64)
- func DecrementMemoryBuffers(size int64)
- func DeepCopy[T any](src *T) (*T, error)
- func DeleteKey(key string, purpose string)
- func EnsureDiskCacheDir() error
- func GenerateQiniuToken(accessKey, secretKey string, req QiniuAuthRequest) (string, error)
- func GenerateRandomString(length int) string
- func GenerateSecureToken(length int) (string, error)
- func GenerateVerificationCode(length int) string
- func GetAudioDuration(ctx context.Context, f io.ReadSeeker, ext string) (duration float64, err error)
- func GetBoolEnv(key string) bool
- func GetBoolValue(db *gorm.DB, key string) bool
- func GetDBTimestamp(db *gorm.DB, driver string) int64
- func GetDiskCacheDir() string
- func GetDiskCacheInfo() (fileCount int, totalSize int64, err error)
- func GetDiskCacheMaxSizeBytes() int64
- func GetDiskCachePath() string
- func GetDiskCacheThresholdBytes() int64
- func GetEnv(key string) string
- func GetFloatEnv(key string) float64
- func GetFloatEnvWithDefault(key string, defaultValue float64) float64
- func GetIPLocation(ip string) (string, string, string, error)
- func GetIPLocationCN(ip string) (string, string, string, error)
- func GetIPLocationGlobal(ip string) (string, string, string, error)
- func GetIntEnv(key string) int64
- func GetIntEnvWithDefault(key string, defaultValue int) int
- func GetIntValue(db *gorm.DB, key string, defaultVal int) int
- func GetRealAddressByIP(ip string) string
- func GetSupportedLanguages() []string
- func GetTimeString() string
- func GetTimestamp() int64
- func GetValue(db *gorm.DB, key string) string
- func HTMLToPlainText(s string) string
- func IncrementDiskCacheHits()
- func IncrementDiskFiles(size int64)
- func IncrementMemoryBuffers(size int64)
- func IncrementMemoryCacheHits()
- func InitDatabase(logWrite io.Writer, driver, dsn string) (*gorm.DB, error)
- func InitGlobalCache(maxSize int, expiration time.Duration)
- func IsDiskCacheAvailable(requestSize int64) bool
- func IsDiskCacheEnabled() bool
- func IsIP(s string) bool
- func IsInternalIP(ip string) bool
- func IsIpInCIDRList(ip net.IP, cidrList []string) bool
- func IsPrivateIP(ip net.IP) bool
- func JoinHTMLBodyAfterTranslation(prefix, translatedInner, suffix string) string
- func LoadAutoloads(db *gorm.DB)
- func LoadEnv(env string) error
- func LoadEnvs(objPtr any)
- func LoadModuleEnvs(module string, appEnv string) error
- func LookupEnv(key string) (value string, found bool)
- func MakeMigrates(db *gorm.DB, insts []any) error
- func Monitor()
- func NormalizeFramePeriod(d string) time.Duration
- func ParseIP(s string) net.IP
- func RandCredentialAPIKey() string
- func RandNumberText(n int) string
- func RandString(n int) string
- func RandText(n int) string
- func ReadDiskCacheFile(filePath string) ([]byte, error)
- func ReadDiskCacheFileString(filePath string) (string, error)
- func ReadFile(filename string) ([]byte, error)
- func RegisterVerificationCodeWithKey(key string, code string, purpose string)
- func RemoveDiskCacheFile(filePath string) error
- func RemoveEmoji(text string) string
- func RemoveEmojiFromJSON(jsonStr string) string
- func RenderMailHTML(tplStr string, data map[string]any) (string, error)
- func RenderMailText(tplStr string, data map[string]any) (string, error)
- func ResetDiskCacheStats()
- func ResetDiskCacheUsage()
- func SafeCall(f func() error, failHandle func(error)) error
- func SafeSendBool(ch chan bool, value bool) (closed bool)
- func SafeSendString(ch chan string, value string) (closed bool)
- func SafeSendStringTimeout(ch chan string, value string, timeout int) (closed bool)
- func SetDiskCacheConfig(config DiskCacheConfig)
- func SetPerformanceMonitorConfig(config PerformanceMonitorConfig)
- func SetValue(db *gorm.DB, key, value, format string, autoload, public bool)
- func ShouldUseDiskCache(dataSize int64) bool
- func SignAccessToken(p AccessPayload, secret string, ttl time.Duration) (string, error)
- func SignRefreshToken(p RefreshPayload, secret string, ttl time.Duration) (string, error)
- func SplitHTMLBodyForTranslation(s string) (prefix, inner, suffix string)
- func StartPyroScope() error
- func StartSystemMonitor()
- func StructAsMap(form any, fields []string) (vals map[string]any)
- func SyncDiskCacheStats()
- func TOTPKeyToPNGDataURL(key *otp.Key, pngSize int) (string, error)
- func TranslateLong(t *MyMemoryTranslator, text, from, to string, maxRunes int, ...) (string, error)
- func ValidateTOTP(code, secret string) bool
- func ValidateURLWithFetchSetting(urlStr string, enableSSRFProtection, allowPrivateIp bool, ...) error
- func VerifyCodeWithKey(key string, code string, purpose string) bool
- func WriteDiskCacheFile(cacheType DiskCacheType, data []byte) (string, error)
- func WriteDiskCacheFileString(cacheType DiskCacheType, data string) (string, error)
- func WriteFile(filename string, data []byte) error
- type AccessPayload
- type Config
- type DiskCacheConfig
- type DiskCacheStats
- type DiskCacheType
- type DiskSpaceInfo
- type ExpiredLRUCache
- type IPGeolocationResponse
- type IPLocationResponse
- type MyMemoryResponse
- type MyMemoryTranslator
- type PerformanceMonitorConfig
- type QiniuAuthRequest
- type RefreshPayload
- type SSRFProtection
- type SigHandler
- type SigHandlerEvent
- type SignalHandler
- type Signals
- func (s *Signals) Clear(events ...string)
- func (s *Signals) Connect(event string, handler SignalHandler) uint
- func (s *Signals) Disconnect(event string, id uint)
- func (s *Signals) Emit(event string, sender any, params ...any)
- func (s *Signals) EmitAsync(ctx context.Context, event string, sender any, params ...any) (*task.Task[asyncEmitPayload, struct{}], error)
- func (s *Signals) SetAsyncPoolFactory(fn func() *task.TaskPool[asyncEmitPayload, struct{}])
- type Snowflake
- type SystemStatus
- type TOTPSetup
Constants ¶
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" )
const ( AccessIssuer = "lingvoice" RefreshIssuer = "lingvoice.refresh" )
Issuers separate access vs refresh JWTs so tokens are not interchangeable.
const ( // DefaultTOTPIssuer authenticator apps 显示的发行方名称(otpauth URL)。 DefaultTOTPIssuer = "LingVoice" // DefaultTOTPSecretSize TOTP 密钥字节长度。 DefaultTOTPSecretSize = 32 // DefaultTOTPQRPNGSize 二维码 PNG 边长(像素)。 DefaultTOTPQRPNGSize = 256 )
const ( EmailVerificationPurpose = "v" PasswordResetPurpose = "r" )
Variables ¶
var DefaultSSRFProtection = &SSRFProtection{ AllowPrivateIp: false, DomainFilterMode: true, DomainList: []string{}, IpFilterMode: true, IpList: []string{}, AllowedPorts: []int{}, }
DefaultSSRFProtection 默认SSRF防护配置
var ( // ErrInvalidToken is returned when the token is malformed, expired, or signature-invalid. ErrInvalidToken = errors.New("jwt: invalid token") )
var Validate *validator.Validate
var VerificationValidMinutes = 10
Functions ¶
func CheckValue ¶
func ChunkRunes ¶
ChunkRunes splits s into substrings of at most maxRunes runes (UTF-8 safe).
func CleanupOldDiskCacheFiles ¶
CleanupOldDiskCacheFiles 清理旧的缓存文件 maxAge: 文件最大存活时间 注意:此函数只删除文件,不更新统计(因为无法知道每个文件的原始大小)
func ComputeSampleByteCount ¶
ComputeSampleByteCount calculates bytes per millisecond for given audio parameters
func ConfigureConnectionPool ¶
ConfigureConnectionPool configure database connection pool
func CreateDiskCacheFile ¶
func CreateDiskCacheFile(cacheType DiskCacheType) (string, *os.File, error)
CreateDiskCacheFile 创建磁盘缓存文件 cacheType: 缓存类型(body/file) 返回文件路径和文件句柄
func DecrementMemoryBuffers ¶
func DecrementMemoryBuffers(size int64)
DecrementMemoryBuffers 减少内存缓存计数
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 ¶
GenerateRandomString 生成指定长度的随机字符串
func GenerateSecureToken ¶
GenerateSecureToken generate a fixed-length secure token
func GetAudioDuration ¶
func GetAudioDuration(ctx context.Context, f io.ReadSeeker, ext string) (duration float64, err error)
GetAudioDuration 使用纯 Go 库获取音频文件的时长(秒)。 它不再依赖外部的 ffmpeg 或 ffprobe 程序。
func GetBoolEnv ¶
func GetDBTimestamp ¶
GetDBTimestamp returns a UNIX timestamp from database time. 分布式系统必须用数据库统一时间 如果你的服务部署在多台服务器每台服务器时间可能差几秒~几分钟会导致: 订单时间错乱, 登录日志时间不对, 数据统计异常 Falls back to application time on error.
func GetDiskCacheDir ¶
func GetDiskCacheDir() string
GetDiskCacheDir 获取统一的磁盘缓存目录 注意:每次调用都会重新计算,以响应配置变化
func GetDiskCacheInfo ¶
GetDiskCacheInfo 获取磁盘缓存目录信息
func GetDiskCacheMaxSizeBytes ¶
func GetDiskCacheMaxSizeBytes() int64
GetDiskCacheMaxSizeBytes 获取磁盘缓存最大大小(字节)
func GetDiskCacheThresholdBytes ¶
func GetDiskCacheThresholdBytes() int64
GetDiskCacheThresholdBytes 获取磁盘缓存阈值(字节)
func GetFloatEnv ¶
func GetFloatEnvWithDefault ¶
GetFloatEnvWithDefault gets float environment variable with default value
func GetIPLocation ¶
GetIPLocation 获取 IP 地理位置(自动选择国内/国外接口) 返回:国家、城市、完整地址、错误
func GetIPLocationCN ¶
GetIPLocationCN 强制使用国内接口查询 IP 地址(更准)
func GetIPLocationGlobal ¶
GetIPLocationGlobal 强制使用国际接口查询 IP 地址
func GetIntEnvWithDefault ¶
GetIntEnvWithDefault gets int environment variable with default value
func GetRealAddressByIP ¶
GetRealAddressByIP 兼容旧接口:只返回地址字符串
func GetSupportedLanguages ¶
func GetSupportedLanguages() []string
GetSupportedLanguages returns list of supported language codes
func GetTimeString ¶
func GetTimeString() string
func GetTimestamp ¶
func GetTimestamp() int64
func HTMLToPlainText ¶
HTMLToPlainText strips tags and style-bearing markup, keeps approximate line breaks, preserves {{.Var}} text.
func IncrementMemoryBuffers ¶
func IncrementMemoryBuffers(size int64)
IncrementMemoryBuffers 增加内存缓存计数
func InitGlobalCache ¶
func IsDiskCacheAvailable ¶
IsDiskCacheAvailable 检查是否可以创建新的磁盘缓存
func IsPrivateIP ¶
func JoinHTMLBodyAfterTranslation ¶
JoinHTMLBodyAfterTranslation reverses SplitHTMLBodyForTranslation.
func LoadAutoloads ¶
func LoadEnv ¶
LoadEnv loads a single file: `.env`, or `.env.{env}` when env is non-empty (legacy helper).
func LoadModuleEnvs ¶
LoadModuleEnvs loads layered env files for one deployable binary (auth, server, sip, …):
- .env-{module}
- .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 NormalizeFramePeriod ¶
ValidateAndNormalizeDuration uses different validation logic with explicit bounds checking
func RandCredentialAPIKey ¶
func RandCredentialAPIKey() string
RandCredentialAPIKey 生成用户凭证密钥,形如 sk- 前缀 + 随机段,总长 48(与 credential.key char(48) 一致)。
func RandNumberText ¶
func RandString ¶
func ReadDiskCacheFile ¶
ReadDiskCacheFile 读取磁盘缓存文件
func ReadDiskCacheFileString ¶
ReadDiskCacheFileString 读取磁盘缓存文件为字符串
func RemoveDiskCacheFile ¶
RemoveDiskCacheFile 删除磁盘缓存文件
func RemoveEmojiFromJSON ¶
removeEmojiFromJSON 从 JSON 字符串中移除 emoji(仅从字符串值中移除,保持 JSON 结构)
func RenderMailHTML ¶
RenderMailHTML 使用 html/template 渲染邮件 HTML(占位符与模版中 {{.Key}} 一致,自动转义值)。
func RenderMailText ¶
RenderMailText 使用 text/template 渲染纯文本主题等(占位符 {{.Key}};未传键按 zero 处理)。
func SafeSendBool ¶
func SafeSendString ¶
func SafeSendStringTimeout ¶
SafeSendStringTimeout send, return true, else return false
func SetDiskCacheConfig ¶
func SetDiskCacheConfig(config DiskCacheConfig)
SetDiskCacheConfig 设置磁盘缓存配置
func SetPerformanceMonitorConfig ¶
func SetPerformanceMonitorConfig(config PerformanceMonitorConfig)
SetPerformanceMonitorConfig 设置性能监控配置
func ShouldUseDiskCache ¶
ShouldUseDiskCache 判断是否应该使用磁盘缓存
func SignAccessToken ¶
SignAccessToken issues an HS256 JWT with subject user:<id> and standard time claims.
func SignRefreshToken ¶
SignRefreshToken issues a refresh JWT (distinct issuer from access).
func SplitHTMLBodyForTranslation ¶
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 TOTPKeyToPNGDataURL ¶
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 ¶
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 WriteDiskCacheFile ¶
func WriteDiskCacheFile(cacheType DiskCacheType, data []byte) (string, error)
WriteDiskCacheFile 写入数据到磁盘缓存文件 返回文件路径
func WriteDiskCacheFileString ¶
func WriteDiskCacheFileString(cacheType DiskCacheType, data string) (string, error)
WriteDiskCacheFileString 写入字符串到磁盘缓存文件
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 ¶
type DiskCacheConfig ¶
type DiskCacheConfig struct {
// Enabled 是否启用磁盘缓存
Enabled bool
// ThresholdMB 触发磁盘缓存的请求体大小阈值(MB)
ThresholdMB int
// MaxSizeMB 磁盘缓存最大总大小(MB)
MaxSizeMB int
// Path 磁盘缓存目录
Path string
}
DiskCacheConfig 磁盘缓存配置(由 performance_setting 包更新)
type DiskCacheStats ¶
type DiskCacheStats struct {
// 当前活跃的磁盘缓存文件数
ActiveDiskFiles int64 `json:"active_disk_files"`
// 当前磁盘缓存总大小(字节)
CurrentDiskUsageBytes int64 `json:"current_disk_usage_bytes"`
// 当前内存缓存数量
ActiveMemoryBuffers int64 `json:"active_memory_buffers"`
// 当前内存缓存总大小(字节)
CurrentMemoryUsageBytes int64 `json:"current_memory_usage_bytes"`
// 磁盘缓存命中次数
DiskCacheHits int64 `json:"disk_cache_hits"`
// 内存缓存命中次数
MemoryCacheHits int64 `json:"memory_cache_hits"`
// 磁盘缓存最大限制(字节)
DiskCacheMaxBytes int64 `json:"disk_cache_max_bytes"`
// 磁盘缓存阈值(字节)
DiskCacheThresholdBytes int64 `json:"disk_cache_threshold_bytes"`
}
DiskCacheStats 磁盘缓存统计信息
type DiskCacheType ¶
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 ¶
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 ¶
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 (*Signals) Disconnect ¶
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 ¶
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 ¶
type SystemStatus ¶
SystemStatus 系统状态信息
Source Files
¶
- access.go
- audio.go
- caches.go
- configs.go
- copy.go
- dbs.go
- dbs_sqlite.go
- dbs_time.go
- disk_cache.go
- disk_cache_config.go
- go-channel.go
- htmlbody_split.go
- htmlplaintext.go
- ip.go
- issuers.go
- mailtpl_render.go
- performance_config.go
- pprof.go
- pyro.go
- qiniu_auth.go
- random.go
- refresh.go
- signals.go
- ssrf_protection.go
- system_monitor.go
- system_monitor_unix.go
- totp.go
- translator.go
- utils.go
- validate.go
- verification.go