utils

package module
v0.16.0 Latest Latest
Warning

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

Go to latest
Published: May 16, 2026 License: MIT Imports: 39 Imported by: 1

README

go-utils

一些常用的工具函数。

安装与导入

  • 使用 Go Modules:
go get github.com/jiaopengzi/go-utils@latest

或指定版本:

go get github.com/jiaopengzi/go-utils@v0.1.0

模块维护

清理依赖:

go mod tidy

在代码中导入

示例导入:

import "github.com/jiaopengzi/go-utils"

Documentation

Overview

Package utils 工具包

Index

Constants

View Source
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.")        // 分布式锁获取失败
)
View Source
const (
	TagStart = "start" // 标签开始
	TagEnd   = "end"   // 标签结束
)
View Source
const ColCount = "COUNT(*) as count"

ColCount 是一个常量, 用于 SQL 查询中统计行数

Variables

AllMarkdownPayType 所有的 markdown 付费类型

Functions

func AddQueryParams

func AddQueryParams(baseURL string, params map[string]string) (string, error)

AddQueryParams 向 baseURL 添加查询参数,返回完整的 URL

func AppendToFile

func AppendToFile(path string, data []byte, perm os.FileMode) error

AppendToFile 将 data 追加到 path 文件中, 如果文件不存在则创建, 如果文件存在则将给定内容追加到指定文件

func CalcMinAmountWithRatioAndFloor added in v0.3.0

func CalcMinAmountWithRatioAndFloor(amount int64, opts ...Option) (int64, error)

CalcMinAmountWithRatioAndFloor 计算最小金额, 基于比例和底线金额

  • amount: 原始金额(分)
  • opts: 可选参数, 用于配置计算的比例精度、分子因子和最小金额

返回计算后的金额(分), 如果计算结果小于底线金额则返回底线金额(分), 否则返回计算结果(分)

func CheckContentHash added in v0.2.1

func CheckContentHash(file *bytes.Reader, targetHash string, opts ...HAOptionFunc) (bool, error)

CheckContentHash 根据文件内容 file 检查哈希值是否匹配目标哈希值 targetHash, 可通过 WithAlgorithm 选项指定哈希算法

func CheckGormRowsAffected added in v0.4.0

func CheckGormRowsAffected(result *gorm.DB) error

CheckGormRowsAffected 检查 GORM 操作结果的 RowsAffected 字段

func CheckIfDirIsEmpty

func CheckIfDirIsEmpty(dir string) (bool, error)

CheckIfDirIsEmpty 检查目录是否为空

func CheckRegex

func CheckRegex(regex, str string) bool

CheckRegex 通过 regex 正则表达式校验 str 字符串是否匹配

func ComparePasswords

func ComparePasswords(hashedPassword, password string) bool

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 CreateDir

func CreateDir(path string, perm os.FileMode) error

CreateDir 根据路径 path 创建文件夹, 如果文件夹不存在则创建

func DecryptAES

func DecryptAES(encryptStr string, keyStr string, ivStr ...string) (string, error)

DecryptAES 解密函数, 对加密过的字符串进行解密, 返回解密后的字符串.

  • encryptStr: 需要解密的字符串
  • keyStr: 密钥
  • ivStr: 初始化向量(可选)。未传时自动检测 GCM 或旧 CBC 格式,传入时使用 AES-CBC

func DeepCopy

func DeepCopy[T any](data T) (T, error)

DeepCopy 将 data 递归地深拷贝任意类型的值,深拷贝到一个新的变量中

func DeleteFile

func DeleteFile(path string) error

DeleteFile 删除文件 path

func DeleteFileRemoveDirRecursiveRemoveEmptyParents

func DeleteFileRemoveDirRecursiveRemoveEmptyParents(path string, stopAtDir string) error

DeleteFileRemoveDirRecursiveRemoveEmptyParents 删除文件并递归删除空目录,直到遇到 stopAtDir

func Difference

func Difference(listA, listB []string) []string

Difference 并行计算两个字符串切片的差集,返回 listA 中所有不在 listB 中的元素。

func EncodeURL

func EncodeURL(s string) string

EncodeURL 使用 URL 编码对字符串 s 进行编码

func EncryptAES

func EncryptAES(plainText string, keyStr string, ivStr ...string) (string, error)

EncryptAES 加密函数, 对明文字符串进行加密 返回加密后的字符串

  • plainText: 需要加密的明文字符串
  • keyStr: 密钥
  • ivStr: 初始化向量(可选)。未传时使用 AES-GCM + 随机 nonce,传入时使用 AES-CBC

func FlattenDirectoryStructure

func FlattenDirectoryStructure(dir string, delimiter ...string) string

FlattenDirectoryStructure 将目录结构 dir 扁平化, 使用 delimiter 作为分隔符,默认为"-";比如 FlattenDirectoryStructure("a/b/c") => a-b-c

func GenDateSQLConditionYM added in v0.3.0

func GenDateSQLConditionYM(field string, ym *YearMonth) string

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

func GenerateAESKeyAndIV() (string, string, error)

GenerateAESKeyAndIV 生成 AES 加密算法的 32 位的 key 和 16 位的 iv

func GenerateB64Str added in v0.2.0

func GenerateB64Str(numEvenBytes int) (string, error)

GenerateB64Str 根据 numEvenBytes 生成指定长度的 Base64 字符串

func GenerateBinaryData

func GenerateBinaryData(numEvenBytes int) ([]byte, error)

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

func GenerateHashedPassword(password string, bcryptCost int) (string, error)

GenerateHashedPassword 生成密码的哈希值

func GenerateHasher added in v0.2.1

func GenerateHasher(opts ...HAOptionFunc) hash.Hash

GenerateHasher 生成哈希对象, 可通过 WithAlgorithm 选项指定哈希算法

func GenerateHexStr

func GenerateHexStr(numEvenBytes int) (string, error)

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

func GenerateMarkdownDetail(summary, content string) string

GenerateMarkdownDetail 生成 markdown 详情内容

func GenerateMarkdownTable

func GenerateMarkdownTable(headers []string, rows [][]string) string

GenerateMarkdownTable 生成 markdown 表格

func GenerateSlugByName

func GenerateSlugByName(s string) (string, error)

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 GetCurrentYear

func GetCurrentYear() int

GetCurrentYear

func GetDisableExpiresAtSeconds

func GetDisableExpiresAtSeconds(disableExpiresAt any) uint64

GetDisableExpiresAtSeconds 获取禁用过期时间, 返回禁用时间 单位秒 0 未被禁用

func GetFileName

func GetFileName(path string) string

GetFileName 根据文件路径 path 获取文件名

func GetFileNameNoExt

func GetFileNameNoExt(path string) string

GetFileNameNoExt 根据文件路径 path 获取不带扩展名的文件名

func GetFutureTime

func GetFutureTime(seconds int64) time.Time

GetFutureTime 获取未来时间, 返回未来时间, 参数为秒

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

func GetUniqueMachineID(ipOrMac string) (uint16, error)

GetUniqueMachineID 通过 IP 或 MAC 地址获取机器ID

func InitDir

func InitDir(path string, perm os.FileMode) error

InitDir 初始化文件夹 path, 如果文件夹不存在则创建, 如果文件夹存在则删除后再创建

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

func Int64FenToStrYuan(i int64) string

Int64FenToStrYuan 将 int64 转换为字符串包含小数的元 例如 1234 转换为 "12.34" 如果 int64 为 0,则返回 "0.00"

func Int64Ptr

func Int64Ptr(i int64) *int64

Int64Ptr 将 int64 转换为指针

func Int64ToStr

func Int64ToStr(i int64) string

Int64ToStr 将 int64 转字符串

func IntToStr

func IntToStr(i int) string

IntToStr 将 int 转字符串

func IsDirExists

func IsDirExists(path string) bool

IsDirExists 判断目录 path 是否存在

func IsFileExists

func IsFileExists(path string) bool

IsFileExists 判断文件 path 是否存在

func IsFileName

func IsFileName(fileName string) bool

IsFileName 判断 fileName 是否为合法的文件名

func IsImageURL

func IsImageURL(u string) bool

IsImageURL 判断字符串 u 是否为图片 URL

func IsInterfaceNil

func IsInterfaceNil(i any) bool

IsInterfaceNil 判断接口变量是否为 nil

对于接口变量 i,reflect.ValueOf(i) 返回的是 i 持有的具体值,而不是 i 本身。 可能的情况有两种: 1. 接口变量本身为 nil:这意味着接口变量的类型信息和数据指针都是 nil。 2. 接口变量的具体类型为 nil:这意味着接口变量的类型信息不为 nil,但数据指针为 nil。

func IsPointer added in v0.2.0

func IsPointer(v any) bool

IsPointer 检查传入的 v 是否是指针

func IsRelativePath

func IsRelativePath(path string) bool

IsRelativePath 判断 path 是否为相对路径

func IsSlicesEqual

func IsSlicesEqual[T any](sliceSrc, sliceTar []T) bool

IsSlicesEqual 判断两个切片是否相等

func IsSlicesEqualByField

func IsSlicesEqualByField[T any](sliceSrc, sliceTar []T, fieldNames []string) (bool, error)

IsSlicesEqualByField 判断两个切片是否相等,指定结构体的某些字段需要相等,如果指定字段外其他的字段不相等就返回错误.

func IsTimeoutError added in v0.2.1

func IsTimeoutError(err error) bool

IsTimeoutError 判断是否是超时错误

func IsWebvtt

func IsWebvtt(content string) (bool, string)

IsWebvtt 判断是否为 Webvtt 字幕

func JoinURL

func JoinURL(baseURL string, paths ...string) (string, error)

JoinURL 拼接 baseURL 和路径元素,返回完整的 URL, paths 可以是多个

func MakeSet

func MakeSet(slice []string) map[string]struct{}

MakeSet 将字符串切片转换为 map

func MapKeysToSlice

func MapKeysToSlice[K comparable, V any](m map[K]V) []K

MapKeysToSlice 将 map 的 key 转换为切片, 保留 map 键的类型

func Paginate

func Paginate[T any](page *Page[T]) func(db *gorm.DB) *gorm.DB

Paginate 返回一个gorm.DB作用域函数,用于应用分页查询

func ParseBool

func ParseBool(s string, fallback bool) bool

ParseBool 根据字符串 s 解析布尔值,如果解析失败则返回 fallback

func ParseNumber

func ParseNumber(s string, fallback int) int

ParseNumber 根据字符串 s 解析数字,如果解析失败则返回 fallback

func ParsePath

func ParsePath(u *url.URL, fallback string) string

ParsePath 解析 URL 的路径部分,如果为空则返回 fallback

func PlayKeyDecryptAES2String

func PlayKeyDecryptAES2String(playKeyEncrypt string) (string, error)

PlayKeyDecryptAES2String 使用 AES 解密算法用 encryptKey 解密 playKey 生成解密后的密钥 encryptPlayKey 16进制字符串

func PlayKeyEncryptAES2Base64

func PlayKeyEncryptAES2Base64(playKey string, playKeyKey string, ivStr ...string) (string, error)

PlayKeyEncryptAES2Base64 使用 AES 加密算法用 playKeyKey + iv 加密 playKey 生成加密后的密钥 encryptedPlayKeyBase64 字符串; 再拼接 倒序后的playKeyKey + encryptedPlayKeyBase64 + 倒序后的validateIVStr

  • playKey: 播放密钥
  • playKeyKey: 播放密钥的加密密钥
  • ivStr: 初始化向量(可选)

func PrintByte added in v0.6.0

func PrintByte(s string, perLine ...int)

PrintByte 打印字符串的字节切片表示形式 例如: "abc" -> []byte{99,98,97} 第二个参数 perLine 指定每行打印的 byte 个数,可选,默认 16

func ReadFile

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

ReadFile 读取文件 path 的内容, 返回文件数据和可能的错误

func ReadFileToString

func ReadFileToString(filePath string) (string, error)

ReadFileToString 读取文件 filePath 到字符串

func RemoveDir

func RemoveDir(path string) error

RemoveDir 根据 path 删除文件夹

func RemoveDirAndRecursiveRemoveEmptyParents

func RemoveDirAndRecursiveRemoveEmptyParents(dir string, stopAtDir string) error

RemoveDirAndRecursiveRemoveEmptyParents 删除目录并向上递归删除空目录,直到遇到 stopAtDir

func RemoveDuplicateElement

func RemoveDuplicateElement(list []string) []string

RemoveDuplicateElement 移除字符串切片中的重复元素,返回一个只包含唯一元素的新切片。

func ReplaceMarkdownPayTagToEmpty

func ReplaceMarkdownPayTagToEmpty(input string, payType MarkdownPayType) string

ReplaceMarkdownPayTagToEmpty 替换 markdown 付费标签为空标签.

  • input, 原始 markdown 内容.
  • payType, 需要替换的付费标签类型.

返回值 string, 替换后的 markdown 内容.

关键约束:

  1. fenced code block (``` ... ```) 内的付费标签视为字面量, 原样保留.
  2. 行内代码 (`...`) 内的付费标签视为字面量, 原样保留. inline code 不跨行 (CommonMark).
  3. 仅当付费标签存在配对的 endTag 时才替换为空标签; 缺少 endTag 时, 当作普通文本保留, 避免吞掉文末.

func ReplaceMarkdownPayTagsToEmpty

func ReplaceMarkdownPayTagsToEmpty(input string) string

ReplaceMarkdownPayTagsToEmpty 替换多个 markdown 付费标签为空标签, 一次遍历处理

func ReverseSlice added in v0.6.0

func ReverseSlice[T any](s []T) []T

ReverseSlice 传入一个切片, 然后倒序输出该切片

func ReverseString

func ReverseString(str string) string

ReverseString 将字符串逆序排列并返回

func SleepWithContext

func SleepWithContext(ctx context.Context, duration time.Duration) error

SleepWithContext 在上下文中等待

func SliceStrToUint64

func SliceStrToUint64(list []string) []uint64

SliceStrToUint64 字符串切片转 uint64 切片

func SliceUint64ToStr

func SliceUint64ToStr(list []uint64) []string

SliceUint64ToStr uint64 切片转字符串切片

func SplitCommand

func SplitCommand(input string, keepQuotes bool) []string

SplitCommand 按照空格拆分字符串, 但是引号内的内容不拆分; keepQuotes 为 true 保留引号, 为 false 不保留, 例如 "ls -l" 拆分为 ["ls", "-l"]

func StrIsUint64

func StrIsUint64(s any) bool

StrIsUint64 将字符串转换为 uint64

func StrToInt

func StrToInt(s string) int

StrToInt 将字符串转换为 int

func StrToInt64

func StrToInt64(s string) int64

StrToInt64 将字符串转换为 int64

func StrToPtr

func StrToPtr(s string) *string

StrToPtr 将字符串返回为指针

func StrToSQLNullTime

func StrToSQLNullTime(str string) sql.NullTime

StrToSQLNullTime 将字符串时间转换为 sql.NullTime

func StrToUint64

func StrToUint64(s string) uint64

StrToUint64 将字符串转换为 uint64

func StrYuanToInt64Fen

func StrYuanToInt64Fen(s string) int64

StrYuanToInt64Fen 将字符串包含小数的元转换为 int64 分 例如 "12.34" 转换为 1234 如果字符串无法转换为数字,则返回 0

func Transaction added in v0.3.0

func Transaction(db *gorm.DB, txFunc func(tx *gorm.DB) error) (err error)

WithTransaction 处理事务的函数 借鉴 GORM 原生 Transaction 实现, 使用 panicked 标志模式 优点:

  1. 不使用 recover(), 让 panic 自然传播到上层(如 Gin Recovery)
  2. 统一的 defer 回滚逻辑, 覆盖 panic、业务错误、commit 失败所有场景
  3. 添加日志记录便于问题排查
  4. 支持嵌套事务, 使用 SavePoint 实现

func Uint64ToStr

func Uint64ToStr(i uint64) string

Uint64ToStr 将 uint64 转字符串

func UnsafeSQLTemplate added in v0.16.0

func UnsafeSQLTemplate(templateStr string, varMap map[string]string) (string, error)

UnsafeSQLTemplate 使用 text/template 将 varMap 中的变量替换到 SQL 模板中并生成 SQL 语句。

警告:本函数直接将变量值拼入 SQL 字符串,不提供任何转义或参数化保护。 严禁传入任何外部用户输入,仅限内部硬编码的列名/表名等可信标识符使用。 新增查询请优先使用参数化 SQL 或 ORM 条件构造。

func WriteFile

func WriteFile(path string, data []byte, perm os.FileMode) error

WriteFile 将 data 写入到 path 文件中, 如果文件不存在则创建, 如果文件存在则覆盖

func YearMonthSelect

func YearMonthSelect(params *YearMonth) (startDate, endDate time.Time)

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

type ClientInfo struct {
	IP        string // IP
	UserAgent string // 用户浏览器信息
}

ClientInfo 日志内容

func GetClientInfo

func GetClientInfo(c *gin.Context) ClientInfo

GetClientInfo 从 *gin.Context 中获取客户端信息 ClientInfo

type Config added in v0.3.0

type Config struct {
	Numerator   int64 // 分子
	Denominator int64 // 分母
	Min         int64 // 最小金额(分)
}

Config 配置结构体

func NewConfig added in v0.3.0

func NewConfig(opts ...Option) *Config

NewConfig 创建配置对象

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

type DirGenerator interface {
	GenerateDir() (string, error) // 生成文件夹 返回文件夹路径和错误信息
}

DirGenerator 文件夹生成器 接口

type FieldMismatchError

type FieldMismatchError struct {
	FieldName string
	Index     int
}

FieldMismatchError 自定义错误类型,用于描述字段不匹配的错误

func (*FieldMismatchError) Error

func (e *FieldMismatchError) Error() string

Error 实现 error 接口 Error 方法

type GenerateDirOptions

type GenerateDirOptions struct {
	IsMkdirLocal       bool // 是否创建本地文件夹
	FileNameHashLength int  // 文件名哈希长度
}

GenerateDirOptions 生成文件夹选项

type HAOption added in v0.6.0

type HAOption struct {
	Algorithm HashAlgorithm
}

HAOption 签名选项

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 JpzError

type JpzError string

func (JpzError) Error

func (e JpzError) Error() string

Error 实现 error 接口 Error 方法

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

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

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 WithDenominatorOption(denominator int64) Option

func WithMinAmountOption added in v0.3.0

func WithMinAmountOption(min int64) Option

WithMinAmountOption

func WithNumeratorOption added in v0.3.0

func WithNumeratorOption(numerator int64) Option

type Page

type Page[T any] struct {
	*PageBase
	Records []T `json:"records"` // 返回的当前页数据记录
}

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 WithHighlight

func WithHighlight(flag bool) PaginateOption

WithHighlight 设置高亮

func WithPageSizes

func WithPageSizes(pageSizes []int64) PaginateOption

WithPageSizes 设置分页大小

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

type SonyflakeSettingsProvider func() (sonyflake.Settings, error)

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 YM

type YM interface {
	// 生成横线连接的日期别名 YYYY-MM
	GenDateSlug() string
}

YM 日期时间格式化接口

type YearMonth

type YearMonth struct {
	Year  int
	Month int
}

YearMonth 用于传递年份和月份的参数

func ValidateYearMonthFormat

func ValidateYearMonthFormat(ym string) (bool, *YearMonth)

ValidateYearMonthFormat 验证年月格式

func (YearMonth) GenDateSlug

func (ym YearMonth) GenDateSlug() string

GenDateSlug 生成日期别名

type YearMonthLastModTime

type YearMonthLastModTime struct {
	YearMonth
	LastModTime time.Time
}

func (YearMonthLastModTime) GenDateSlug

func (ym YearMonthLastModTime) GenDateSlug() string

GenDateSlug 生成日期别名

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
gin
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 单独定义通用的数据类型

Jump to

Keyboard shortcuts

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