Documentation
¶
Overview ¶
Package utils 工具包
Index ¶
- Constants
- Variables
- func AddQueryParams(baseURL string, params map[string]string) (string, error)
- func AppendToFile(path string, data []byte, perm os.FileMode) error
- func CalcMinAmountWithRatioAndFloor(amount int64, opts ...Option) (int64, error)
- func CheckContentHash(file *bytes.Reader, targetHash string, opts ...HAOptionFunc) (bool, error)
- func CheckGormRowsAffected(result *gorm.DB) error
- func CheckIfDirIsEmpty(dir string) (bool, error)
- func CheckRegex(regex, str string) bool
- func ComparePasswords(hashedPassword, password string) bool
- func ConcurrentQuery[T any](wg *sync.WaitGroup, queryFunc func() (T, error), resultChan chan<- T, ...)
- func CreateDir(path string, perm os.FileMode) error
- func DecryptAES(encryptStr string, keyStr string, ivStr ...string) (string, error)
- func DeepCopy[T any](data T) (T, error)
- func DeleteFile(path string) error
- func DeleteFileRemoveDirRecursiveRemoveEmptyParents(path string, stopAtDir string) error
- func Difference(listA, listB []string) []string
- func EncodeURL(s string) string
- func EncryptAES(plainText string, keyStr string, ivStr ...string) (string, error)
- func FlattenDirectoryStructure(dir string, delimiter ...string) string
- func GenDateSQLConditionYM(field string, ym *YearMonth) string
- func GenerateAESKeyAndIV() (string, string, error)
- func GenerateB64Str(numEvenBytes int) (string, error)
- func GenerateBinaryData(numEvenBytes int) ([]byte, error)
- func GenerateHashByFileContent(file *bytes.Reader, opts ...HAOptionFunc) (string, error)
- func GenerateHashByFilePath(filePath string, opts ...HAOptionFunc) (string, error)
- func GenerateHashByStrContent(str string, opts ...HAOptionFunc) (string, error)
- func GenerateHashedPassword(password string, bcryptCost int) (string, error)
- func GenerateHasher(opts ...HAOptionFunc) hash.Hash
- func GenerateHexStr(numEvenBytes int) (string, error)
- func GenerateIncrementalHash(chunks []io.Reader, opts ...HAOptionFunc) (string, error)
- func GenerateIncrementalHashFromFilePaths(filePaths []string, opts ...HAOptionFunc) (string, error)
- func GenerateMarkdownDetail(summary, content string) string
- func GenerateMarkdownTable(headers []string, rows [][]string) string
- func GenerateSlugByName(s string) (string, error)
- func GetCurrentTimestampNano() int64
- func GetCurrentTimestampNanoStr() string
- func GetCurrentYear() int
- func GetDisableExpiresAtSeconds(disableExpiresAt any) uint64
- func GetFileName(path string) string
- func GetFileNameNoExt(path string) string
- func GetFutureTime(seconds int64) time.Time
- func GetMarkdownEmptyPayTag(payType MarkdownPayType) string
- func GetMarkdownEmptyPayTagWithAttr(payType MarkdownPayType, attr string) string
- func GetMarkdownPayTag(payType MarkdownPayType, flag string) string
- func GetUniqueMachineID(ipOrMac string) (uint16, error)
- func InitDir(path string, perm os.FileMode) error
- func InsertFromDetails(db *gorm.DB, fields reflect.Type, values reflect.Value, ...) error
- func Int64FenToStrYuan(i int64) string
- func Int64Ptr(i int64) *int64
- func Int64ToStr(i int64) string
- func IntToStr(i int) string
- func IsDirExists(path string) bool
- func IsFileExists(path string) bool
- func IsFileName(fileName string) bool
- func IsImageURL(u string) bool
- func IsInterfaceNil(i any) bool
- func IsPointer(v any) bool
- func IsRelativePath(path string) bool
- func IsSlicesEqual[T any](sliceSrc, sliceTar []T) bool
- func IsSlicesEqualByField[T any](sliceSrc, sliceTar []T, fieldNames []string) (bool, error)
- func IsTimeoutError(err error) bool
- func IsWebvtt(content string) (bool, string)
- func JoinURL(baseURL string, paths ...string) (string, error)
- func MakeSet(slice []string) map[string]struct{}
- func MapKeysToSlice[K comparable, V any](m map[K]V) []K
- func Paginate[T any](page *Page[T]) func(db *gorm.DB) *gorm.DB
- func ParseBool(s string, fallback bool) bool
- func ParseNumber(s string, fallback int) int
- func ParsePath(u *url.URL, fallback string) string
- func PlayKeyDecryptAES2String(playKeyEncrypt string) (string, error)
- func PlayKeyEncryptAES2Base64(playKey string, playKeyKey string, ivStr ...string) (string, error)
- func PrintByte(s string, perLine ...int)
- func ReadFile(path string) ([]byte, error)
- func ReadFileToString(filePath string) (string, error)
- func RemoveDir(path string) error
- func RemoveDirAndRecursiveRemoveEmptyParents(dir string, stopAtDir string) error
- func RemoveDuplicateElement(list []string) []string
- func ReplaceMarkdownPayTagToEmpty(input string, payType MarkdownPayType) string
- func ReplaceMarkdownPayTagsToEmpty(input string) string
- func ReverseSlice[T any](s []T) []T
- func ReverseString(str string) string
- func SleepWithContext(ctx context.Context, duration time.Duration) error
- func SliceStrToUint64(list []string) []uint64
- func SliceUint64ToStr(list []uint64) []string
- func SplitCommand(input string, keepQuotes bool) []string
- func StrIsUint64(s any) bool
- func StrToInt(s string) int
- func StrToInt64(s string) int64
- func StrToPtr(s string) *string
- func StrToSQLNullTime(str string) sql.NullTime
- func StrToUint64(s string) uint64
- func StrYuanToInt64Fen(s string) int64
- func Transaction(db *gorm.DB, txFunc func(tx *gorm.DB) error) (err error)
- func Uint64ToStr(i uint64) string
- func UnsafeSQLTemplate(templateStr string, varMap map[string]string) (string, error)
- func WriteFile(path string, data []byte, perm os.FileMode) error
- func YearMonthSelect(params *YearMonth) (startDate, endDate time.Time)
- type ChunkSubDir
- type ClientInfo
- type Config
- type DateTimeLayout
- type DirGenerator
- type FieldMismatchError
- type GenerateDirOptions
- type HAOption
- type HAOptionFunc
- type HashAlgorithm
- type HighlightOption
- type JpzError
- type Location
- type MarkdownPayType
- type Option
- type Page
- type PageBase
- type PageES
- type PageSizesOption
- type PaginateConfig
- type PaginateOption
- type ShardedMutex
- type SonyflakeGenerator
- type SonyflakeSettingsProvider
- type SourceExcludesOption
- type SourceIncludesOption
- type WithDenominator
- type WithMinAmount
- type WithNumerator
- type YM
- type YearMonth
- type YearMonthLastModTime
Constants ¶
const ( ErrNotEmpty = JpzError("not_empty.") // 不能为空 ErrSlugTooLong = JpzError("slug_too_long.") // slug 过长 ErrRedisNoAuth = JpzError("NOAUTH Authentication required.") // redis 未授权 ErrOrderNotOwn = JpzError("order is not own.") // 订单不属于当前用户 ErrOrderCheckoutExpired = JpzError("order checkout is expired.") // 订单结算信息已过期 ErrRefundWeChatNotEnough = JpzError("refund wechat not enough.") // 微信退款余额不足 ErrRefundAlipayNotEnough = JpzError("refund alipay not enough.") // 支付宝退款余额不足 ErrTokenInvalidClaims = JpzError("invalid_token_claims.") // token 声明无效 ErrTokenInvalid = JpzError("token_is_invalid.") // token 无效 ErrTokenInvalidType = JpzError("invalid_token_type.") // token 类型无效 ErrTokenMissingUserID = JpzError("token_missing_user_id.") // token 缺少用户ID ErrTokenMissingJwi = JpzError("token_missing_jwi.") // token 缺少 jwi ErrGormRowsAffectedZero = JpzError("gorm_rows_affected_zero.") // gorm 影响行数为0 ErrTimeout = JpzError("timeout.") // 超时 ErrInvalidSignature = JpzError("invalid_signature.") // 签名无效 ErrTimestampDiffExceeded = JpzError("timestamp_difference_exceeded.") // 时间戳差异超出允许范围 ErrRequestIDNotFound = JpzError("request_id_not_found.") // 请求ID未找到 ErrDistributedLockFailed = JpzError("distributed_lock_failed.") // 分布式锁获取失败 )
const ( TagStart = "start" // 标签开始 TagEnd = "end" // 标签结束 )
const ColCount = "COUNT(*) as count"
ColCount 是一个常量, 用于 SQL 查询中统计行数
Variables ¶
var AllMarkdownPayType = []MarkdownPayType{ MarkdownPayRead, MarkdownPayDownload, MarkdownPayVideo, }
AllMarkdownPayType 所有的 markdown 付费类型
Functions ¶
func AddQueryParams ¶
AddQueryParams 向 baseURL 添加查询参数,返回完整的 URL
func AppendToFile ¶
AppendToFile 将 data 追加到 path 文件中, 如果文件不存在则创建, 如果文件存在则将给定内容追加到指定文件
func CalcMinAmountWithRatioAndFloor ¶ added in v0.3.0
CalcMinAmountWithRatioAndFloor 计算最小金额, 基于比例和底线金额
- amount: 原始金额(分)
- opts: 可选参数, 用于配置计算的比例精度、分子因子和最小金额
返回计算后的金额(分), 如果计算结果小于底线金额则返回底线金额(分), 否则返回计算结果(分)
func CheckContentHash ¶ added in v0.2.1
CheckContentHash 根据文件内容 file 检查哈希值是否匹配目标哈希值 targetHash, 可通过 WithAlgorithm 选项指定哈希算法
func CheckGormRowsAffected ¶ added in v0.4.0
CheckGormRowsAffected 检查 GORM 操作结果的 RowsAffected 字段
func CheckIfDirIsEmpty ¶
CheckIfDirIsEmpty 检查目录是否为空
func ComparePasswords ¶
ComparePasswords 根据哈希值验证密码是否匹配
func ConcurrentQuery ¶
func ConcurrentQuery[T any](wg *sync.WaitGroup, queryFunc func() (T, error), resultChan chan<- T, errorChan chan<- error)
ConcurrentQuery 通用并发查询
- wg: *sync.WaitGroup 等待组
- queryFunc: func() (T, error) 查询函数
- resultChan: chan<- T 结果通道
- errorChan: chan<- error 错误通道
func DecryptAES ¶
DecryptAES 解密函数, 对加密过的字符串进行解密, 返回解密后的字符串.
- encryptStr: 需要解密的字符串
- keyStr: 密钥
- ivStr: 初始化向量(可选)。未传时自动检测 GCM 或旧 CBC 格式,传入时使用 AES-CBC
func DeleteFileRemoveDirRecursiveRemoveEmptyParents ¶
DeleteFileRemoveDirRecursiveRemoveEmptyParents 删除文件并递归删除空目录,直到遇到 stopAtDir
func Difference ¶
Difference 并行计算两个字符串切片的差集,返回 listA 中所有不在 listB 中的元素。
func EncryptAES ¶
EncryptAES 加密函数, 对明文字符串进行加密 返回加密后的字符串
- plainText: 需要加密的明文字符串
- keyStr: 密钥
- ivStr: 初始化向量(可选)。未传时使用 AES-GCM + 随机 nonce,传入时使用 AES-CBC
func FlattenDirectoryStructure ¶
FlattenDirectoryStructure 将目录结构 dir 扁平化, 使用 delimiter 作为分隔符,默认为"-";比如 FlattenDirectoryStructure("a/b/c") => a-b-c
func GenDateSQLConditionYM ¶ added in v0.3.0
GenDateSQLConditionYM 生成字段 field 关于年月形式日期 sql 查询条件为字符串. - field: 字段名 - ym: 年月指针 示例:
ym := &YearMonth{Year: 2021, Month: 1}
condition := GenDateSQLConditionYM("created_at", ym)
// condition 结果: "created_at BETWEEN '2021-01-01 00:00:00' AND '2021-01-31 23:59:59'"
func GenerateAESKeyAndIV ¶
GenerateAESKeyAndIV 生成 AES 加密算法的 32 位的 key 和 16 位的 iv
func GenerateB64Str ¶ added in v0.2.0
GenerateB64Str 根据 numEvenBytes 生成指定长度的 Base64 字符串
func GenerateBinaryData ¶
GenerateBinaryData 根据 numEvenBytes(必须是偶数) 生成指定长度的二进制数据
func GenerateHashByFileContent ¶ added in v0.2.1
func GenerateHashByFileContent(file *bytes.Reader, opts ...HAOptionFunc) (string, error)
GenerateHashByFileContent 通过文件内容 file 生成哈希值, 可通过 WithAlgorithm 选项指定哈希算法
func GenerateHashByFilePath ¶ added in v0.2.1
func GenerateHashByFilePath(filePath string, opts ...HAOptionFunc) (string, error)
GenerateHashByFilePath 通过 filePath 生成哈希值, 可通过 WithAlgorithm 选项指定哈希算法
func GenerateHashByStrContent ¶ added in v0.2.1
func GenerateHashByStrContent(str string, opts ...HAOptionFunc) (string, error)
GenerateHashByStrContent 通过字符串 生成哈希值, 可通过 WithAlgorithm 选项指定哈希算法
func GenerateHashedPassword ¶
GenerateHashedPassword 生成密码的哈希值
func GenerateHasher ¶ added in v0.2.1
func GenerateHasher(opts ...HAOptionFunc) hash.Hash
GenerateHasher 生成哈希对象, 可通过 WithAlgorithm 选项指定哈希算法
func GenerateHexStr ¶
GenerateHexStr 根据 numEvenBytes(必须是偶数) 生成指定长度的十六进制字符串
func GenerateIncrementalHash ¶ added in v0.2.1
func GenerateIncrementalHash(chunks []io.Reader, opts ...HAOptionFunc) (string, error)
GenerateIncrementalHash 逐个分片复制内容到哈希对象, 然后增量计算哈希值, 可通过 WithAlgorithm 选项指定哈希算法
func GenerateIncrementalHashFromFilePaths ¶ added in v0.2.1
func GenerateIncrementalHashFromFilePaths(filePaths []string, opts ...HAOptionFunc) (string, error)
GenerateIncrementalHashFromFilePaths 根据 filePaths 逐个分片复制内容到哈希对象, 然后增量计算哈希值, 可通过 WithAlgorithm 选项指定哈希算法
func GenerateMarkdownDetail ¶
GenerateMarkdownDetail 生成 markdown 详情内容
func GenerateMarkdownTable ¶
GenerateMarkdownTable 生成 markdown 表格
func GenerateSlugByName ¶
GenerateSlugByName 根据名称生成 slug
func GetCurrentTimestampNano ¶ added in v0.2.1
func GetCurrentTimestampNano() int64
GetCurrentTimestampNano 获取当前时间戳(纳秒)
func GetCurrentTimestampNanoStr ¶ added in v0.2.1
func GetCurrentTimestampNanoStr() string
GetCurrentTimestampNanoStr 获取当前时间戳字符串(纳秒)
func GetDisableExpiresAtSeconds ¶
GetDisableExpiresAtSeconds 获取禁用过期时间, 返回禁用时间 单位秒 0 未被禁用
func GetFileNameNoExt ¶
GetFileNameNoExt 根据文件路径 path 获取不带扩展名的文件名
func GetMarkdownEmptyPayTag ¶
func GetMarkdownEmptyPayTag(payType MarkdownPayType) string
GetMarkdownEmptyPayTag 获取 markdown 空的付费标签
func GetMarkdownEmptyPayTagWithAttr ¶ added in v0.14.0
func GetMarkdownEmptyPayTagWithAttr(payType MarkdownPayType, attr string) string
GetMarkdownEmptyPayTagWithAttr 获取带属性的 markdown 空付费标签
func GetMarkdownPayTag ¶
func GetMarkdownPayTag(payType MarkdownPayType, flag string) string
GetMarkdownPayTag 获取 markdown 付费标签
func GetUniqueMachineID ¶
GetUniqueMachineID 通过 IP 或 MAC 地址获取机器ID
func InsertFromDetails ¶ added in v0.3.0
func InsertFromDetails(db *gorm.DB, fields reflect.Type, values reflect.Value, processField func(i int, field reflect.StructField, value reflect.Value) error) error
InsertFromDetails 从结构体中插入数据, processField 用于处理字段的函数.
func Int64FenToStrYuan ¶
Int64FenToStrYuan 将 int64 转换为字符串包含小数的元 例如 1234 转换为 "12.34" 如果 int64 为 0,则返回 "0.00"
func IsInterfaceNil ¶
IsInterfaceNil 判断接口变量是否为 nil
对于接口变量 i,reflect.ValueOf(i) 返回的是 i 持有的具体值,而不是 i 本身。 可能的情况有两种: 1. 接口变量本身为 nil:这意味着接口变量的类型信息和数据指针都是 nil。 2. 接口变量的具体类型为 nil:这意味着接口变量的类型信息不为 nil,但数据指针为 nil。
func IsSlicesEqual ¶
IsSlicesEqual 判断两个切片是否相等
func IsSlicesEqualByField ¶
IsSlicesEqualByField 判断两个切片是否相等,指定结构体的某些字段需要相等,如果指定字段外其他的字段不相等就返回错误.
func MapKeysToSlice ¶
func MapKeysToSlice[K comparable, V any](m map[K]V) []K
MapKeysToSlice 将 map 的 key 转换为切片, 保留 map 键的类型
func ParseNumber ¶
ParseNumber 根据字符串 s 解析数字,如果解析失败则返回 fallback
func PlayKeyDecryptAES2String ¶
PlayKeyDecryptAES2String 使用 AES 解密算法用 encryptKey 解密 playKey 生成解密后的密钥 encryptPlayKey 16进制字符串
func PlayKeyEncryptAES2Base64 ¶
PlayKeyEncryptAES2Base64 使用 AES 加密算法用 playKeyKey + iv 加密 playKey 生成加密后的密钥 encryptedPlayKeyBase64 字符串; 再拼接 倒序后的playKeyKey + encryptedPlayKeyBase64 + 倒序后的validateIVStr
- playKey: 播放密钥
- playKeyKey: 播放密钥的加密密钥
- ivStr: 初始化向量(可选)
func PrintByte ¶ added in v0.6.0
PrintByte 打印字符串的字节切片表示形式 例如: "abc" -> []byte{99,98,97} 第二个参数 perLine 指定每行打印的 byte 个数,可选,默认 16
func ReadFileToString ¶
ReadFileToString 读取文件 filePath 到字符串
func RemoveDirAndRecursiveRemoveEmptyParents ¶
RemoveDirAndRecursiveRemoveEmptyParents 删除目录并向上递归删除空目录,直到遇到 stopAtDir
func RemoveDuplicateElement ¶
RemoveDuplicateElement 移除字符串切片中的重复元素,返回一个只包含唯一元素的新切片。
func ReplaceMarkdownPayTagToEmpty ¶
func ReplaceMarkdownPayTagToEmpty(input string, payType MarkdownPayType) string
ReplaceMarkdownPayTagToEmpty 替换 markdown 付费标签为空标签.
- input, 原始 markdown 内容.
- payType, 需要替换的付费标签类型.
返回值 string, 替换后的 markdown 内容.
关键约束:
- fenced code block (``` ... ```) 内的付费标签视为字面量, 原样保留.
- 行内代码 (`...`) 内的付费标签视为字面量, 原样保留. inline code 不跨行 (CommonMark).
- 仅当付费标签存在配对的 endTag 时才替换为空标签; 缺少 endTag 时, 当作普通文本保留, 避免吞掉文末.
func ReplaceMarkdownPayTagsToEmpty ¶
ReplaceMarkdownPayTagsToEmpty 替换多个 markdown 付费标签为空标签, 一次遍历处理
func ReverseSlice ¶ added in v0.6.0
func ReverseSlice[T any](s []T) []T
ReverseSlice 传入一个切片, 然后倒序输出该切片
func SleepWithContext ¶
SleepWithContext 在上下文中等待
func SliceStrToUint64 ¶
SliceStrToUint64 字符串切片转 uint64 切片
func SliceUint64ToStr ¶
SliceUint64ToStr uint64 切片转字符串切片
func SplitCommand ¶
SplitCommand 按照空格拆分字符串, 但是引号内的内容不拆分; keepQuotes 为 true 保留引号, 为 false 不保留, 例如 "ls -l" 拆分为 ["ls", "-l"]
func StrToSQLNullTime ¶
StrToSQLNullTime 将字符串时间转换为 sql.NullTime
func StrYuanToInt64Fen ¶
StrYuanToInt64Fen 将字符串包含小数的元转换为 int64 分 例如 "12.34" 转换为 1234 如果字符串无法转换为数字,则返回 0
func Transaction ¶ added in v0.3.0
WithTransaction 处理事务的函数 借鉴 GORM 原生 Transaction 实现, 使用 panicked 标志模式 优点:
- 不使用 recover(), 让 panic 自然传播到上层(如 Gin Recovery)
- 统一的 defer 回滚逻辑, 覆盖 panic、业务错误、commit 失败所有场景
- 添加日志记录便于问题排查
- 支持嵌套事务, 使用 SavePoint 实现
func UnsafeSQLTemplate ¶ added in v0.16.0
UnsafeSQLTemplate 使用 text/template 将 varMap 中的变量替换到 SQL 模板中并生成 SQL 语句。
警告:本函数直接将变量值拼入 SQL 字符串,不提供任何转义或参数化保护。 严禁传入任何外部用户输入,仅限内部硬编码的列名/表名等可信标识符使用。 新增查询请优先使用参数化 SQL 或 ORM 条件构造。
func YearMonthSelect ¶
YearMonthSelect 选择年月区间, 月不填写为参数年整年,年月都不填写为 当前日期整年;返回开始时间和结束时间(比较大小的时候为左闭右开)
Types ¶
type ChunkSubDir ¶
type ChunkSubDir struct {
// 必填项
CreatedAt time.Time // 数据库中的创建日期
ID uint64 // ID
HashStr string // hash 字符串
PartNumbers int64 // 分片数量
// 可选项
Delimiter string // 分隔符
DateTimeLayout DateTimeLayout // 日期时间布局
HashStrPrefixLength int // 取用 Hash 字符串前缀长度
RootDir string // 根目录
Permission os.FileMode // 文件夹权限
}
ChunkSubDir 分片存储子目录
func (*ChunkSubDir) GenerateDir ¶
func (cd *ChunkSubDir) GenerateDir(opts *GenerateDirOptions) (string, error)
GenerateDir 根据 opts 选项生成文件夹
type ClientInfo ¶
ClientInfo 日志内容
func GetClientInfo ¶
func GetClientInfo(c *gin.Context) ClientInfo
GetClientInfo 从 *gin.Context 中获取客户端信息 ClientInfo
type DateTimeLayout ¶
type DateTimeLayout string
DateTimeLayout 文件夹的日期时间布局
const ( DateTimeLayoutYear DateTimeLayout = "year" DateTimeLayoutMonth DateTimeLayout = "month" DateTimeLayoutDay DateTimeLayout = "day" DateTimeLayoutHour DateTimeLayout = "hour" DateTimeLayoutMin DateTimeLayout = "min" DateTimeLayoutSec DateTimeLayout = "sec" )
定义日期时间布局全局常量
type DirGenerator ¶
DirGenerator 文件夹生成器 接口
type FieldMismatchError ¶
FieldMismatchError 自定义错误类型,用于描述字段不匹配的错误
func (*FieldMismatchError) Error ¶
func (e *FieldMismatchError) Error() string
Error 实现 error 接口 Error 方法
type GenerateDirOptions ¶
GenerateDirOptions 生成文件夹选项
type HAOptionFunc ¶ added in v0.6.0
type HAOptionFunc func(*HAOption)
HAOptionFunc 签名选项函数
func WithAlgorithm ¶ added in v0.2.1
func WithAlgorithm(alg HashAlgorithm) HAOptionFunc
WithAlgorithm 设置哈希算法
type HashAlgorithm ¶ added in v0.2.1
type HashAlgorithm string
HashAlgorithm 哈希类型
const ( SHA256 HashAlgorithm = "SHA-256" SHA384 HashAlgorithm = "SHA-384" SHA512 HashAlgorithm = "SHA-512" )
定义哈希类型全局常量
type HighlightOption ¶
type HighlightOption struct {
Highlight bool
}
HighlightOption 高亮选项
func (HighlightOption) Apply ¶
func (o HighlightOption) Apply(config *PaginateConfig)
Apply 配置 Config
type Location ¶
type Location struct {
Status string `json:"status"`
Country string `json:"country"`
RegionName string `json:"regionName"`
City string `json:"city"`
}
Location IP地址归属地
func GetIPLocation ¶
GetIPLocation 根据 ip 地址, 获取 ip 地址归属地 Location
type MarkdownPayType ¶
type MarkdownPayType string
MarkdownPayType markdown 付费类型
const ( MarkdownPayRead MarkdownPayType = "pay-read" // 付费阅读 MarkdownPayDownload MarkdownPayType = "pay-download" // 付费下载 MarkdownPayVideo MarkdownPayType = "pay-video" // 付费视频 )
type Option ¶ added in v0.3.0
type Option interface {
Apply(*Config)
}
Option 包含 Apply 方法, 用来配置 Config
func WithDenominatorOption ¶ added in v0.3.0
func WithMinAmountOption ¶ added in v0.3.0
WithMinAmountOption
func WithNumeratorOption ¶ added in v0.3.0
type Page ¶
Page 通用泛型分页结构体
func (*Page[T]) SelectPages ¶
func (page *Page[T]) SelectPages(db, query *gorm.DB, opts ...PaginateOption) error
SelectPages [T any] 执行分页查询并返回结果
- db: 数据库连接
- query: 查询语句
- opts: 可选参数,用于配置分页大小
type PageBase ¶
type PageBase struct {
Total int64 `json:"total"` // 总记录数
CurrentPage int64 `json:"current_page"` // 当前页
PageSize int64 `json:"page_size"` // 分页大小
PageCount int64 `json:"page_count"` // 总页数
PageSizes []int64 `json:"page_sizes"` // 分页大小列表 10,20,50,100
}
PageBase 分页基础结构体
func (*PageBase) CalculatePageParams ¶
func (page *PageBase) CalculatePageParams()
CalculatePageParams 实现 PageInterface 接口
type PageES ¶
type PageES struct {
*PageBase
Records []json.RawMessage `json:"records"` // 返回的当前页数据记录
Highlight []map[string][]string `json:"highlight"` // 高亮字段
}
PageES elasticsearch 分页结构体, 结果直接是 json.RawMessage 类型,不用指定具体的类型
func (*PageES) SelectPagesES ¶
func (page *PageES) SelectPagesES(client *elasticsearch.TypedClient, index string, req *search.Request, ctx context.Context, opts ...PaginateOption) error
SelectPagesES 执行分页查询并返回结果
- client: Elasticsearch 客户端
- index: 索引名称
- query: 查询请求
- sourceIncludes: 返回的字段
- opts: 可选参数,用于配置分页大小
type PageSizesOption ¶
type PageSizesOption struct {
PageSizes []int64
}
PageSizesOption 分页大小选项
func (PageSizesOption) Apply ¶
func (o PageSizesOption) Apply(config *PaginateConfig)
Apply 配置 Config
type PaginateConfig ¶
type PaginateConfig struct {
PageSizes []int64 // 分页大小
SourceIncludes []string // 需要返回的字段
SourceExcludes []string // 需要排除返回的字段
Highlight bool // 是否高亮
}
PaginateConfig 分页查询配置
type PaginateOption ¶
type PaginateOption interface {
Apply(*PaginateConfig)
}
PaginateOption 包含 Apply 方法,用来配置 PaginateConfig
func WithSourceExcludes ¶
func WithSourceExcludes(sourceExcludes []string) PaginateOption
WithSourceExcludes 设置需要排除返回的字段
func WithSourceIncludes ¶
func WithSourceIncludes(sourceIncludes []string) PaginateOption
WithSourceIncludes 设置需要返回的字段
type ShardedMutex ¶
type ShardedMutex struct {
// contains filtered or unexported fields
}
ShardedMutex 是一个基于 key 的分片互斥锁, 用于减少锁竞争.
func NewShardedMutex ¶
func NewShardedMutex(shardCount int) (*ShardedMutex, error)
NewShardedMutex 创建一个新的分片互斥锁. shardCount 必须是 2 的幂(如 32, 64, 128), 否则会返回错误.
func (*ShardedMutex) Lock ¶
func (sm *ShardedMutex) Lock(key uint64)
Lock 根据 key 对应的分片加锁; key 通常为用户 ID、设备 ID 等唯一标识.
func (*ShardedMutex) Unlock ¶
func (sm *ShardedMutex) Unlock(key uint64)
Unlock 根据 key 对应的分片解锁; key 必须与 Lock 时使用的 key 相同.
type SonyflakeGenerator ¶ added in v0.15.0
type SonyflakeGenerator struct {
// contains filtered or unexported fields
}
SonyflakeGenerator 封装延迟初始化且可复用的雪花 ID 生成器. 它会在首次生成 ID 时初始化一次底层实例, 后续调用复用同一个序列状态.
func NewSonyflakeGenerator ¶ added in v0.15.0
func NewSonyflakeGenerator(settingsProvider SonyflakeSettingsProvider) *SonyflakeGenerator
NewSonyflakeGenerator 创建一个延迟初始化的雪花 ID 生成器. settingsProvider 会在首次调用 NextID 时执行, 用于读取配置并构造 sonyflake.Settings.
func (*SonyflakeGenerator) NextID ¶ added in v0.15.0
func (generator *SonyflakeGenerator) NextID() (uint64, error)
NextID 生成一个全局唯一的雪花 ID. 当首次初始化失败时, 会返回初始化错误并保持失败状态, 避免后续继续使用无效实例.
type SonyflakeSettingsProvider ¶ added in v0.15.0
SonyflakeSettingsProvider 定义雪花生成器初始化时使用的配置提供函数. 返回值中的 MachineID 可以继续使用项目侧的配置或运行时环境计算.
type SourceExcludesOption ¶
type SourceExcludesOption struct {
SourceExcludes []string
}
SourceExcludesOption 需要排除返回的字段
func (SourceExcludesOption) Apply ¶
func (o SourceExcludesOption) Apply(config *PaginateConfig)
Apply 配置 Config
type SourceIncludesOption ¶
type SourceIncludesOption struct {
SourceIncludes []string
}
SourceIncludesOption 需要返回的字段
func (SourceIncludesOption) Apply ¶
func (o SourceIncludesOption) Apply(config *PaginateConfig)
Apply 配置 Config
type WithDenominator ¶ added in v0.3.0
type WithDenominator struct {
Denominator int64
}
WithDenominator 设置比例的分母
func (WithDenominator) Apply ¶ added in v0.3.0
func (w WithDenominator) Apply(cfg *Config)
Apply 实现 Option 接口的 Apply 方法
type WithMinAmount ¶ added in v0.3.0
type WithMinAmount struct {
Min int64
}
WithMinAmount 设置最小金额
func (WithMinAmount) Apply ¶ added in v0.3.0
func (w WithMinAmount) Apply(cfg *Config)
Apply 实现 Option 接口的 Apply 方法
type WithNumerator ¶ added in v0.3.0
type WithNumerator struct {
Numerator int64
}
WithNumerator 设置比例的分子
func (WithNumerator) Apply ¶ added in v0.3.0
func (w WithNumerator) Apply(cfg *Config)
Apply 实现 Option 接口的 Apply 方法
type YearMonth ¶
YearMonth 用于传递年份和月份的参数
func ValidateYearMonthFormat ¶
ValidateYearMonthFormat 验证年月格式
type YearMonthLastModTime ¶
func (YearMonthLastModTime) GenDateSlug ¶
func (ym YearMonthLastModTime) GenDateSlug() string
GenDateSlug 生成日期别名
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package cron 定时任务
|
Package cron 定时任务 |
|
Package validators 请求参数校验器
|
Package validators 请求参数校验器 |
|
Package email 提供 SMTP 邮件发送工具, 支持 STARTTLS (587) 与隐式 TLS (465) 连接池.
|
Package email 提供 SMTP 邮件发送工具, 支持 STARTTLS (587) 与隐式 TLS (465) 连接池. |
|
Package logger 日志记录工具
|
Package logger 日志记录工具 |
|
middleware
|
|
|
Package model 基础业务模型
|
Package model 基础业务模型 |
|
Package pay 支付相关内容
|
Package pay 支付相关内容 |
|
redis
|
|
|
bloom
Package bloom 布隆过滤器.
|
Package bloom 布隆过滤器. |
|
cache
Package cache 缓存核心工具
|
Package cache 缓存核心工具 |
|
lock
Package lock 业务锁,负责业务锁的管理
|
Package lock 业务锁,负责业务锁的管理 |
|
stream
Package stream redis stream 消息队列 包含生产者和消费者
|
Package stream redis stream 消息队列 包含生产者和消费者 |
|
stream/consumer
Package consumer redis stream 消费者核心
|
Package consumer redis stream 消费者核心 |
|
stream/producer
Package core redis stream 生产者核心
|
Package core redis stream 生产者核心 |
|
Package res 响应信息
|
Package res 响应信息 |
|
Package rescode 响应状态码
|
Package rescode 响应状态码 |
|
Package types 单独定义通用的数据类型
|
Package types 单独定义通用的数据类型 |