utils

package
v0.3.1 Latest Latest
Warning

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

Go to latest
Published: Feb 19, 2026 License: MIT Imports: 18 Imported by: 0

Documentation

Index

Examples

Constants

View Source
const (
	// 常用字符集编号
	CharsetBig5ChineseCI       = 1   // big5_chinese_ci
	CharsetLatin2CzechCS       = 2   // latin2_czech_cs
	CharsetDec8SwedishCI       = 3   // dec8_swedish_ci
	CharsetCp850GeneralCI      = 4   // cp850_general_ci
	CharsetLatin1German1CI     = 5   // latin1_german1_ci
	CharsetHp8EnglishCI        = 6   // hp8_english_ci
	CharsetKoi8rGeneralCI      = 7   // koi8r_general_ci
	CharsetLatin1SwedishCI     = 8   // latin1_swedish_ci
	CharsetLatin2GeneralCI     = 9   // latin2_general_ci
	CharsetSwe7SwedishCI       = 10  // swe7_swedish_ci
	CharsetAsciiGeneralCI      = 11  // ascii_general_ci
	CharsetUjisJapaneseCI      = 12  // ujis_japanese_ci
	CharsetSjisJapaneseCI      = 13  // sjis_japanese_ci
	CharsetCp1251BulgarianCI   = 14  // cp1251_bulgarian_ci
	CharsetLatin1DanishCI      = 15  // latin1_danish_ci
	CharsetHebrewGeneralCI     = 16  // hebrew_general_ci
	CharsetTis620ThaiCI        = 18  // tis620_thai_ci
	CharsetEuckrKoreanCI       = 19  // euckr_korean_ci
	CharsetLatin7EstonianCS    = 20  // latin7_estonian_cs
	CharsetLatin2HungarianCI   = 21  // latin2_hungarian_ci
	CharsetKoi8uGeneralCI      = 22  // koi8u_general_ci
	CharsetCp1251UkrainianCI   = 23  // cp1251_ukrainian_ci
	CharsetGb2312ChineseCI     = 24  // gb2312_chinese_ci
	CharsetGreekGeneralCI      = 25  // greek_general_ci
	CharsetCp1250GeneralCI     = 26  // cp1250_general_ci
	CharsetLatin2CroatianCI    = 27  // latin2_croatian_ci
	CharsetGbkChineseCI        = 28  // gbk_chinese_ci
	CharsetCp1257LithuanianCI  = 29  // cp1257_lithuanian_ci
	CharsetLatin5TurkishCI     = 30  // latin5_turkish_ci
	CharsetLatin1German2CI     = 31  // latin1_german2_ci
	CharsetArmscii8GeneralCI   = 32  // armscii8_general_ci
	CharsetUtf8GeneralCI       = 33  // utf8_general_ci (utf8)
	CharsetUtf8mb4GeneralCI    = 45  // utf8mb4_general_ci (utf8mb4)
	CharsetUtf8mb4Bin          = 46  // utf8mb4_bin
	CharsetLatin1SpanishCI     = 47  // latin1_spanish_ci
	CharsetCp1256GeneralCI     = 57  // cp1256_general_ci
	CharsetCp866GeneralCI      = 58  // cp866_general_ci
	CharsetKeybcs2GeneralCI    = 59  // keybcs2_general_ci
	CharsetMacceGeneralCI      = 60  // macce_general_ci
	CharsetMacromanGeneralCI   = 61  // macroman_general_ci
	CharsetCp852GeneralCI      = 62  // cp852_general_ci
	CharsetLatin7GeneralCI     = 63  // latin7_general_ci
	CharsetLatin7GeneralCS     = 64  // latin7_general_cs
	CharsetMacceBin            = 65  // macce_bin
	CharsetCp1250CroatianCI    = 66  // cp1250_croatian_ci
	CharsetUtf8mb4UnicodeCI    = 224 // utf8mb4_unicode_ci
	CharsetUtf8mb4IcelandicCI  = 225 // utf8mb4_icelandic_ci
	CharsetUtf8mb4LatvianCI    = 226 // utf8mb4_latvian_ci
	CharsetUtf8mb4RomanianCI   = 227 // utf8mb4_romanian_ci
	CharsetUtf8mb4SlovenianCI  = 228 // utf8mb4_slovenian_ci
	CharsetUtf8mb4PolishCI     = 229 // utf8mb4_polish_ci
	CharsetUtf8mb4EstonianCI   = 230 // utf8mb4_estonian_ci
	CharsetUtf8mb4SpanishCI    = 231 // utf8mb4_spanish_ci
	CharsetUtf8mb4SwedishCI    = 232 // utf8mb4_swedish_ci
	CharsetUtf8mb4TurkishCI    = 233 // utf8mb4_turkish_ci
	CharsetUtf8mb4CzechCI      = 234 // utf8mb4_czech_ci
	CharsetUtf8mb4DanishCI     = 235 // utf8mb4_danish_ci
	CharsetUtf8mb4LithuanianCI = 236 // utf8mb4_lithuanian_ci
	CharsetUtf8mb4SlovakCI     = 237 // utf8mb4_slovak_ci
	CharsetUtf8mb4Spanish2CI   = 238 // utf8mb4_spanish2_ci
	CharsetUtf8mb4RomanCI      = 239 // utf8mb4_roman_ci
	CharsetUtf8mb4PersianCI    = 240 // utf8mb4_persian_ci
	CharsetUtf8mb4EsperantoCI  = 241 // utf8mb4_esperanto_ci
	CharsetUtf8mb4HungarianCI  = 242 // utf8mb4_hungarian_ci
	CharsetUtf8mb4SinhalaCI    = 243 // utf8mb4_sinhala_ci
	CharsetUtf8mb4German2CI    = 244 // utf8mb4_german2_ci
	CharsetUtf8mb4CroatianCI   = 245 // utf8mb4_croatian_ci
	CharsetUtf8mb4Unicode520CI = 246 // utf8mb4_unicode_520_ci
	CharsetUtf8mb4VietnameseCI = 247 // utf8mb4_vietnamese_ci
	CharsetUtf8mb40900AICi     = 255 // utf8mb4_0900_ai_ci (MySQL 8.0默认)
)
View Source
const (
	// UTF-8相关
	CharsetUtf8    = CharsetUtf8GeneralCI    // utf8 (3字节)
	CharsetUtf8mb4 = CharsetUtf8mb4GeneralCI // utf8mb4 (4字节,推荐)

	// 默认字符集
	CharsetDefault = CharsetUtf8mb40900AICi // MySQL 8.0默认字符集

	// 中文相关
	CharsetGBK    = CharsetGbkChineseCI    // gbk
	CharsetGb2312 = CharsetGb2312ChineseCI // gb2312
	CharsetBIG5   = CharsetBig5ChineseCI   // big5

	// 日文相关
	CharsetSjis = CharsetSjisJapaneseCI // sjis
	CharsetUjis = CharsetUjisJapaneseCI // ujis

	// 韩文相关
	CharsetEuckr = CharsetEuckrKoreanCI // euckr

	// 其他常用
	CharsetLatin1 = CharsetLatin1SwedishCI // latin1
	CharsetAscii  = CharsetAsciiGeneralCI  // ascii
)

常用字符集别名

View Source
const (
	// Table errors
	ErrNoSuchTable   = 1146 // ER_NO_SUCH_TABLE
	ErrBadFieldError = 1054 // ER_BAD_FIELD_ERROR

	// Query errors
	ErrParseError  = 1064 // ER_PARSE_ERROR
	ErrEmptyQuery  = 1065 // ER_EMPTY_QUERY
	ErrInterrupted = 1317 // ER_QUERY_INTERRUPTED

	// SQL状态码
	SqlStateNoSuchTable   = "42S02" // Table does not exist
	SqlStateBadFieldError = "42S22" // Column does not exist
	SqlStateSyntaxError   = "42000" // Syntax error or access violation
	SqlStateUnknownError  = "HY000" // General error
)

MySQL错误码常量定义

Variables

View Source
var (
	// ErrPoolClosed indicates that the pool has been closed
	ErrPoolClosed = errors.New("pool is closed")

	// ErrPoolEmpty indicates that the pool has no available resources
	ErrPoolEmpty = errors.New("pool is empty")

	// ErrPoolFull indicates that the pool has reached its maximum capacity
	ErrPoolFull = errors.New("pool is full")

	// ErrInvalidConfig indicates that the pool configuration is invalid
	ErrInvalidConfig = errors.New("invalid pool configuration")

	// ErrResourceClosed indicates that the resource has been closed
	ErrResourceClosed = errors.New("resource is closed")

	// ErrAcquireTimeout indicates that acquiring a resource timed out
	ErrAcquireTimeout = errors.New("acquire timeout")

	// ErrMaxRetries indicates that max retries have been exceeded
	ErrMaxRetries = errors.New("max retries exceeded")
)

Common pool errors

Functions

func Abs

func Abs[T Signed](a T) T

Abs returns the absolute value

func AbsFloat

func AbsFloat(a float64) float64

AbsFloat returns the absolute value of a float64

func AbsInt

func AbsInt(a int) int

AbsInt returns the absolute value of an int

func AbsInt64

func AbsInt64(a int64) int64

AbsInt64 returns the absolute value of an int64

func ApplyFilters

func ApplyFilters(rows []domain.Row, filters []domain.Filter) ([]domain.Row, error)

ApplyFilters applies filters to result rows

func CaptureStackTrace

func CaptureStackTrace(skip int) []string

CaptureStackTrace captures the current call stack trace skip indicates how many callers to skip (0 = include CaptureStackTrace itself)

func CaptureStackTraceWithDepth

func CaptureStackTraceWithDepth(skip, maxDepth int) []string

CaptureStackTraceWithDepth captures the call stack with a custom maximum depth

func Clamp

func Clamp[T Ordered](value, minVal, maxVal T) T

Clamp constrains a value to be within a range [min, max]

func CompareValues

func CompareValues(a, b interface{}, operator string) (bool, error)

CompareValues compares two values with given operator Returns true if comparison matches, false otherwise

Example
// 数值比较
result, _ := CompareValues(10, 5, ">")
fmt.Println(result)
Output:

true

func CompareValuesForSort

func CompareValuesForSort(a, b interface{}) int

CompareValuesForSort compares two values for sorting Returns -1: a < b, 0: a == b, 1: a > b

func CompareValuesForSortWithCollation

func CompareValuesForSortWithCollation(a, b interface{}, collation string) int

CompareValuesForSortWithCollation compares two values for sorting with collation. When collation is empty or binary, falls back to byte-level comparison.

func CompareValuesWithCollation

func CompareValuesWithCollation(a, b interface{}, operator, collation string) (bool, error)

CompareValuesWithCollation compares two values with given operator and collation. When collation is empty or "utf8mb4_bin", falls back to byte-level comparison.

func Contains

func Contains(s, substr string) bool

Contains checks if string contains substring (supports wildcards)

func ContainsSimple

func ContainsSimple(s, substr string) bool

ContainsSimple 简单字符串包含检查

func ContainsSlice

func ContainsSlice[T comparable](slice []T, item T) bool

ContainsSlice checks if a slice contains a specific element

func ContainsSubstring

func ContainsSubstring(s, substr string) bool

ContainsSubstring 检查字符串是否包含子串

func ContainsWord

func ContainsWord(str, word string) bool

ContainsWord checks if word exists in string as independent word

func ConvertBoolColumnsBasedOnSchema added in v0.3.0

func ConvertBoolColumnsBasedOnSchema(row domain.Row, tableInfo *domain.TableInfo)

ConvertBoolColumnsBasedOnSchema converts numeric values to bool for BOOL/BOOLEAN/TINYINT columns This is used for GORM compatibility as MySQL BOOLEAN is an alias for TINYINT(1) and TiDB parser converts BOOLEAN to tinyint

func DeepCopy

func DeepCopy(value interface{}) interface{}

DeepCopy creates a deep copy of basic types (primitive values, slices, maps) For complex types, use json.Marshal/Unmarshal or implement custom copying

func DefaultIfBlank

func DefaultIfBlank(s, defaultValue string) string

DefaultIfBlank returns the default value if the string is blank (empty or whitespace)

func DefaultIfEmpty

func DefaultIfEmpty(s, defaultValue string) string

DefaultIfEmpty returns the default value if the string is empty

func EndsWith

func EndsWith(s, suffix string) bool

EndsWith 检查字符串是否以指定后缀结尾

func FilterSlice

func FilterSlice[T any](slice []T, predicate func(T) bool) []T

FilterSlice filters a slice based on a predicate function

func FindSubstring

func FindSubstring(s, substr string) int

FindSubstring finds substring position (returns character index for Unicode support)

func GenerateHashedPassword

func GenerateHashedPassword(password string) string

GenerateHashedPassword 生成存储在数据库中的哈希密码 这是mysql.user表中的存储格式 格式: *SHA1(SHA1(password))

Example
hash := GenerateHashedPassword("mypassword")
fmt.Println(len(hash))
fmt.Println(hash[:10])
Output:

41
*fabe5482d

func GeneratePasswordHash

func GeneratePasswordHash(password string, salt []byte) string

GeneratePasswordHash 生成MySQL native password hash Algorithm: SHA1(SHA1(password)) ^ SHA1(salt + SHA1(SHA1(password))) 用于MySQL认证协议

func GetCallerFunction

func GetCallerFunction(skip int) string

GetCallerFunction returns the name of the calling function

func GetCallerInfo

func GetCallerInfo(skip int) (function, file string, line int)

GetCallerInfo returns information about the caller at the specified skip level skip=0 returns the caller of GetCallerInfo

func GetCharsetID

func GetCharsetID(charsetName string) uint8

GetCharsetID 根据字符集名称获取字符集编号

Example
id := GetCharsetID("utf8mb4_general_ci")
fmt.Println(id)

id2 := GetCharsetID("utf8")
fmt.Println(id2)

id3 := GetCharsetID("")
fmt.Println(id3)
Output:

45
33
255

func GetCharsetName

func GetCharsetName(charsetID uint8) string

GetCharsetName 根据字符集编号获取字符集名称

Example
name := GetCharsetName(CharsetUtf8mb4)
fmt.Println(name)

name2 := GetCharsetName(CharsetUtf8)
fmt.Println(name2)

name3 := GetCharsetName(0)
fmt.Println(name3)
Output:

utf8mb4_general_ci
utf8_general_ci
unknown

func IndexOfSubstring

func IndexOfSubstring(s, substr string) int

IndexOfSubstring 查找子串位置(按字符索引,支持Unicode)

func IsAcquireTimeout

func IsAcquireTimeout(err error) bool

IsAcquireTimeout checks if the error is ErrAcquireTimeout

func IsBlank

func IsBlank(s string) bool

IsBlank checks if a string is empty or contains only whitespace

func IsEmpty

func IsEmpty(s string) bool

IsEmpty checks if a string is empty

func IsNotBlank

func IsNotBlank(s string) bool

IsNotBlank checks if a string is not empty and not just whitespace

func IsNotEmpty

func IsNotEmpty(s string) bool

IsNotEmpty checks if a string is not empty

func IsPoolClosed

func IsPoolClosed(err error) bool

IsPoolClosed checks if the error is ErrPoolClosed

func IsPoolEmpty

func IsPoolEmpty(err error) bool

IsPoolEmpty checks if the error is ErrPoolEmpty

func JoinWith

func JoinWith(strs []string, sep string) string

JoinWith 用指定分隔符连接字符串数组

func MapErrorCode

func MapErrorCode(err error) (uint16, string)

MapErrorCode 将错误映射到MySQL错误码和SQL状态码 返回 (errorCode, sqlState)

Example
// 表不存在错误
err := errors.New("table 'users' not found")
code, state := MapErrorCode(err)
fmt.Printf("Code: %d, State: %s\n", code, state)

// 列不存在错误
err2 := errors.New("column 'name' not found")
code2, state2 := MapErrorCode(err2)
fmt.Printf("Code: %d, State: %s\n", code2, state2)

// 语法错误
err3 := errors.New("syntax error near 'from'")
code3, state3 := MapErrorCode(err3)
fmt.Printf("Code: %d, State: %s\n", code3, state3)

// 超时错误
code4, state4 := MapErrorCode(context.DeadlineExceeded)
fmt.Printf("Code: %d, State: %s\n", code4, state4)
Output:

Code: 1146, State: 42S02
Code: 1054, State: 42S22
Code: 1064, State: 42000
Code: 1317, State: HY000

func MapKeys

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

MapKeys returns all keys of a map as a slice

func MapOperator

func MapOperator(parserOp string) string

MapOperator 映射parser操作符到标准操作符 支持的parser操作符: gt, gte, lt, lte, eq, ne, ===, !=, like, not like 返回标准SQL操作符: >, >=, <, <=, =, !=, LIKE, NOT LIKE

func MapSlice

func MapSlice[T, U any](slice []T, transform func(T) U) []U

MapSlice transforms each element of a slice using a function

func MapValues

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

MapValues returns all values of a map as a slice

func MatchesAllSubFilters

func MatchesAllSubFilters(row domain.Row, subFilters []domain.Filter) (bool, error)

MatchesAllSubFilters checks if a row matches all sub-filters (AND logic) Returns error immediately if any filter fails with an error

func MatchesAnySubFilter

func MatchesAnySubFilter(row domain.Row, subFilters []domain.Filter) (bool, error)

MatchesAnySubFilter checks if a row matches any sub-filter (OR logic) Returns the first error encountered, but continues matching

func MatchesFilter

func MatchesFilter(row domain.Row, filter domain.Filter) (bool, error)

MatchesFilter checks if a row matches a filter

func MatchesLike

func MatchesLike(value, pattern string) bool

MatchesLike implements SQL LIKE pattern matching. Supports: % (match any sequence of characters), _ (match any single character). Uses a segment-based algorithm: splits the pattern by '%', then matches each literal segment in order. O(n*k) where k = number of segments.

func MatchesLikeWithCollation

func MatchesLikeWithCollation(value, pattern, collation string) bool

MatchesLikeWithCollation performs LIKE matching with collation awareness. For _ci collations, folds both value and pattern to lowercase before matching. For _ai_ci collations, additionally strips accents via NFD decomposition.

func Max

func Max[T Ordered](a, b T) T

Max returns the larger of two values

func MaxInt

func MaxInt(a, b int) int

MaxInt returns the larger of two int values (for compatibility)

func MaxInt64

func MaxInt64(a, b int64) int64

MaxInt64 returns the larger of two int64 values (for compatibility)

func Min

func Min[T Ordered](a, b T) T

Min returns the smaller of two values

func MinInt

func MinInt(a, b int) int

MinInt returns the smaller of two int values (for compatibility)

func MinInt64

func MinInt64(a, b int64) int64

MinInt64 returns the smaller of two int64 values (for compatibility)

func MustParseFloat64

func MustParseFloat64(s string) float64

MustParseFloat64 parses a string to float64, panics on error

func MustParseInt

func MustParseInt(s string) int

MustParseInt parses a string to int, panics on error

func MustParseInt64

func MustParseInt64(s string) int64

MustParseInt64 parses a string to int64, panics on error

func Now

func Now() time.Time

Now returns the current time using the default provider

func PadLeft

func PadLeft(s string, padChar rune, targetLen int) string

PadLeft pads a string on the left with a specified character to reach the target length

func PadRight

func PadRight(s string, padChar rune, targetLen int) string

PadRight pads a string on the right with a specified character to reach the target length

func ParseBool

func ParseBool(s string, defaultValue bool) bool

ParseBool parses a string to bool, returns default value on error Accepts "1", "t", "T", "true", "TRUE", "True" as true Accepts "0", "f", "F", "false", "FALSE", "False" as false

func ParseBoolStrict

func ParseBoolStrict(s string) (bool, error)

ParseBoolStrict parses a string to bool, returns error on failure

func ParseFloat64

func ParseFloat64(s string, defaultValue float64) float64

ParseFloat64 parses a string to float64, returns default value on error

func ParseFloat64Strict

func ParseFloat64Strict(s string) (float64, error)

ParseFloat64Strict parses a string to float64, returns error on failure

func ParseInt

func ParseInt(s string, defaultValue int) int

ParseInt parses a string to int, returns default value on error

func ParseInt64

func ParseInt64(s string, defaultValue int64) int64

ParseInt64 parses a string to int64, returns default value on error

func ParseInt64Strict

func ParseInt64Strict(s string) (int64, error)

ParseInt64Strict parses a string to int64, returns error on failure

func ParseIntStrict

func ParseIntStrict(s string) (int, error)

ParseIntStrict parses a string to int, returns error on failure

func ParseRemoteAddr

func ParseRemoteAddr(remoteAddr string) (string, string)

ParseRemoteAddr parses remote address in format "ip:port" or "[ipv6]:port" Returns (ip, port)

Example
// IPv4 地址
ip, port := ParseRemoteAddr("192.168.1.1:3306")
fmt.Println("IP:", ip, "Port:", port)

// 域名地址
ip2, port2 := ParseRemoteAddr("localhost:3306")
fmt.Println("IP:", ip2, "Port:", port2)
Output:

IP: 192.168.1.1 Port: 3306
IP: localhost Port: 3306

func ParseUint

func ParseUint(s string, defaultValue uint) uint

ParseUint parses a string to uint, returns default value on error

func ParseUint64

func ParseUint64(s string, defaultValue uint64) uint64

ParseUint64 parses a string to uint64, returns default value on error

func ReplaceAll

func ReplaceAll(s, old, new string) string

ReplaceAll replaces all occurrences of old with new in string s

func ResetTimeProvider

func ResetTimeProvider()

ResetTimeProvider resets to the system time provider

func Reverse

func Reverse(s string) string

Reverse reverses a string

func ReverseSlice

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

ReverseSlice reverses a slice in place

func SetTimeProvider

func SetTimeProvider(provider TimeProvider)

SetTimeProvider sets the default time provider (useful for testing)

func Since

func Since(t time.Time) time.Duration

Since returns the time elapsed since t using the default provider

func Sleep

func Sleep(d time.Duration)

Sleep pauses for the given duration using the default provider

func SortedKeys

func SortedKeys[K Ordered, V any](m map[K]V) []K

SortedKeys returns the keys of a map sorted in ascending order

func SortedStringKeys

func SortedStringKeys[V any](m map[string]V) []string

SortedStringKeys returns the string keys of a map sorted in ascending order

func StartsWith

func StartsWith(s, prefix string) bool

StartsWith 检查字符串是否以指定前缀开头

func ToFloat64

func ToFloat64(arg interface{}) (float64, error)

ToFloat64 converts a value to float64

Example
result, _ := ToFloat64(42)
fmt.Println(result)

result2, _ := ToFloat64("3.14")
fmt.Println(result2)

result3, _ := ToFloat64(int32(10))
fmt.Println(result3)

result4, err := ToFloat64("hello")
fmt.Println(result4, err)
Output:

42
3.14
10
0 cannot convert string to float64

func ToInt

func ToInt(arg interface{}) (int, error)

ToInt converts a value to int

func ToInt64

func ToInt64(arg interface{}) (int64, error)

ToInt64 converts a value to int64

Example
result, _ := ToInt64(42.7)
fmt.Println(result)

result2, _ := ToInt64(int32(100))
fmt.Println(result2)

result3, err := ToInt64("hello")
fmt.Println(result3, err)
Output:

42
100
0 cannot convert string to int64

func ToLowerCase

func ToLowerCase(s string) string

ToLowerCase 转小写(兼容包装)

func ToString

func ToString(v interface{}) string

ToString converts any value to string

Example
// 字符串转换
result := ToString("hello")
fmt.Println(result)

result2 := ToString(42)
fmt.Println(result2)

result3 := ToString(3.14)
fmt.Println(result3)

result4 := ToString(true)
fmt.Println(result4)
Output:

hello
42
3.14
true

func TrimPrefix

func TrimPrefix(s, prefix string) string

TrimPrefix removes a prefix from a string if present

func TrimSpace

func TrimSpace(s string) string

TrimSpace trims whitespace from both ends of a string

func TrimSuffix

func TrimSuffix(s, suffix string) string

TrimSuffix removes a suffix from a string if present

func Truncate

func Truncate(s string, maxLen int) string

Truncate truncates a string to the specified maximum length If the string is longer than maxLen, it returns the first maxLen characters with "..." appended If maxLen <= 3, returns the first maxLen characters without ellipsis

func TruncateWithEllipsis

func TruncateWithEllipsis(s string, maxLen int, ellipsis string) string

TruncateWithEllipsis truncates a string with custom ellipsis

func UniqueInt64s

func UniqueInt64s(slice []int64) []int64

UniqueInt64s removes duplicate int64 from a slice

func UniqueInts

func UniqueInts(slice []int) []int

UniqueInts removes duplicate integers from a slice

func UniqueStrings

func UniqueStrings(slice []string) []string

UniqueStrings removes duplicate strings from a slice

func Until

func Until(t time.Time) time.Duration

Until returns the duration until t using the default provider

func VerifyPassword

func VerifyPassword(storedHash string, password string, authResponse []byte, salt []byte) bool

VerifyPassword 验证密码 参数:

  • storedHash: 存储的密码哈希
  • password: 待验证的明文密码
  • authResponse: 客户端发送的认证响应
  • salt: salt数据

返回: 密码是否匹配

func VerifyPasswordWithHash

func VerifyPasswordWithHash(storedHash, password string) bool

VerifyPasswordWithHash 仅验证密码是否匹配存储的哈希 用于测试和直接密码验证

Example
hash := GenerateHashedPassword("mypassword")
result := VerifyPasswordWithHash(hash, "mypassword")
fmt.Println(result)

result2 := VerifyPasswordWithHash(hash, "wrongpassword")
fmt.Println(result2)
Output:

true
false

Types

type CollationEngine

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

CollationEngine provides locale-aware string comparison and sort key generation. It maps MySQL collation names to golang.org/x/text/collate configurations. Collator instances are created per-call because they are NOT goroutine-safe.

func GetGlobalCollationEngine

func GetGlobalCollationEngine() *CollationEngine

GetGlobalCollationEngine returns the global CollationEngine singleton.

func NewCollationEngine

func NewCollationEngine() *CollationEngine

NewCollationEngine creates a new CollationEngine with the supported collation registry.

func (*CollationEngine) Compare

func (e *CollationEngine) Compare(a, b string, collationName string) (int, error)

Compare compares two strings using the specified collation. Returns -1, 0, or 1.

func (*CollationEngine) GetCollationInfo

func (e *CollationEngine) GetCollationInfo(name string) (*CollationInfo, bool)

GetCollationInfo returns metadata for a collation, or (nil, false) if unknown.

func (*CollationEngine) IsAccentInsensitive

func (e *CollationEngine) IsAccentInsensitive(collationName string) bool

IsAccentInsensitive returns true if the named collation is accent-insensitive.

func (*CollationEngine) IsCaseInsensitive

func (e *CollationEngine) IsCaseInsensitive(collationName string) bool

IsCaseInsensitive returns true if the named collation is case-insensitive.

func (*CollationEngine) ListCollations

func (e *CollationEngine) ListCollations() []*CollationInfo

ListCollations returns all registered collations.

func (*CollationEngine) ResolveCollation

func (e *CollationEngine) ResolveCollation(name string) string

ResolveCollation normalizes a collation name, resolving aliases and case differences. Returns the canonical collation name.

func (*CollationEngine) SortKey

func (e *CollationEngine) SortKey(s string, collationName string) ([]byte, error)

SortKey generates a binary sort key for the given string and collation. Sort keys can be compared with bytes.Compare for correct collation ordering.

type CollationInfo

type CollationInfo struct {
	Name              string
	ID                uint8
	Charset           string
	Tag               language.Tag
	CaseInsensitive   bool
	AccentInsensitive bool
	IsBinary          bool
	// contains filtered or unexported fields
}

CollationInfo describes a collation's properties

type FixedTimeProvider

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

FixedTimeProvider returns a fixed time for testing purposes.

func NewFixedTimeProvider

func NewFixedTimeProvider(fixedTime time.Time) *FixedTimeProvider

NewFixedTimeProvider creates a provider that always returns the given time

func (*FixedTimeProvider) Add

func (p *FixedTimeProvider) Add(d time.Duration)

Add advances the fixed time by the given duration

func (*FixedTimeProvider) Now

func (p *FixedTimeProvider) Now() time.Time

Now returns the fixed time

func (*FixedTimeProvider) SetTime

func (p *FixedTimeProvider) SetTime(t time.Time)

SetTime allows updating the fixed time (useful for advancing time in tests)

func (*FixedTimeProvider) Since

func (p *FixedTimeProvider) Since(t time.Time) time.Duration

Since returns the duration since the fixed time

func (*FixedTimeProvider) Sleep

func (p *FixedTimeProvider) Sleep(d time.Duration)

Sleep does nothing in the fixed time provider

func (*FixedTimeProvider) Until

func (p *FixedTimeProvider) Until(t time.Time) time.Duration

Until returns the duration until the fixed time

type MockTimeProvider

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

MockTimeProvider allows full control over time for testing.

func NewMockTimeProvider

func NewMockTimeProvider() *MockTimeProvider

NewMockTimeProvider creates a new mock time provider

func (*MockTimeProvider) Add

func (p *MockTimeProvider) Add(d time.Duration)

Add advances the mock time by the given duration

func (*MockTimeProvider) Now

func (p *MockTimeProvider) Now() time.Time

Now returns the mock current time

func (*MockTimeProvider) SetSleepHook

func (p *MockTimeProvider) SetSleepHook(hook func(d time.Duration))

SetSleepHook sets a custom function to be called on Sleep

func (*MockTimeProvider) SetTime

func (p *MockTimeProvider) SetTime(t time.Time)

SetTime sets the mock current time

func (*MockTimeProvider) Since

func (p *MockTimeProvider) Since(t time.Time) time.Duration

Since returns the duration since t

func (*MockTimeProvider) Sleep

func (p *MockTimeProvider) Sleep(d time.Duration)

Sleep calls the sleep hook if set, otherwise advances time

func (*MockTimeProvider) Until

func (p *MockTimeProvider) Until(t time.Time) time.Duration

Until returns the duration until t

type Ordered

type Ordered interface {
	~int | ~int8 | ~int16 | ~int32 | ~int64 |
		~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr |
		~float32 | ~float64 |
		~string
}

Ordered is a constraint that permits any ordered type.

type PoolError

type PoolError struct {
	Op  string // The operation that failed
	Err error  // The underlying error
}

PoolError represents a pool-related error with additional context

func NewPoolError

func NewPoolError(op string, err error) *PoolError

NewPoolError creates a new PoolError

func (*PoolError) Error

func (e *PoolError) Error() string

Error implements the error interface

func (*PoolError) Unwrap

func (e *PoolError) Unwrap() error

Unwrap returns the underlying error

type Signed

type Signed interface {
	~int | ~int8 | ~int16 | ~int32 | ~int64
}

Signed is a constraint that permits any signed integer type.

type SystemTimeProvider

type SystemTimeProvider struct{}

SystemTimeProvider is the default implementation using real system time.

func NewSystemTimeProvider

func NewSystemTimeProvider() *SystemTimeProvider

NewSystemTimeProvider creates a new SystemTimeProvider

func (*SystemTimeProvider) Now

func (p *SystemTimeProvider) Now() time.Time

Now returns the current system time

func (*SystemTimeProvider) Since

Since returns the time elapsed since t

func (*SystemTimeProvider) Sleep

func (p *SystemTimeProvider) Sleep(d time.Duration)

Sleep pauses the current goroutine for at least the duration d

func (*SystemTimeProvider) Until

Until returns the duration until t

type TimeProvider

type TimeProvider interface {
	// Now returns the current time
	Now() time.Time

	// Since returns the time elapsed since t
	Since(t time.Time) time.Duration

	// Until returns the duration until t
	Until(t time.Time) time.Duration

	// Sleep pauses the current goroutine for at least the duration d
	Sleep(d time.Duration)
}

TimeProvider defines an interface for time-related operations. This abstraction allows for easier testing by enabling time injection.

func GetTimeProvider

func GetTimeProvider() TimeProvider

GetTimeProvider returns the default time provider

Jump to

Keyboard shortcuts

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