# ixUtils **Repository Path**: ixgo/utils ## Basic Information - **Project Name**: ixUtils - **Description**: golang常用函数库 - **Primary Language**: Unknown - **License**: Apache-2.0 - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2025-09-19 - **Last Updated**: 2026-03-25 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # ixUtils - Go 语言工具包 [![Go Version](https://img.shields.io/badge/Go-%3E%3D%201.18-blue.svg)](https://golang.org/) [![License](https://img.shields.io/badge/license-MIT-green.svg)](LICENSE) ixUtils 是一个功能丰富的 Go 语言工具包,提供了日常开发中常用的工具函数,涵盖ID生成、网络工具、数学计算、字符串处理、数组操作、Map操作、结构体操作、错误处理、验证工具、加密解密、HTTP 请求、并发控制、文件操作、时间处理等19个功能模块。 ## ✨ 特性 - 🚀 **高性能**: 优化的算法实现,注重性能 - 🔧 **易用性**: 简洁的 API 设计,开箱即用 - 🛡️ **类型安全**: 使用 Go 泛型,提供类型安全的操作 - 📦 **模块化**: 按功能分类,便于按需使用 - 🧪 **测试完备**: 完整的单元测试覆盖 - 📚 **文档详细**: 详细的使用说明和示例 - 🌐 **分布式友好**: 支持雪花ID、链路追踪等分布式场景 - 📊 **业务导向**: 提供订单ID、API密钥等业务专用功能 ## 📁 功能模块 ### 🆔 ID生成工具 (id.go) 强大的ID生成工具,支持UUID、雪花ID、短ID等多种ID生成方式,满足分布式系统和各种业务场景的需求。 #### 主要函数 **UUID生成** - `GenerateUUID() string` - 生成标准UUID (RFC 4122 Version 4) - `GenerateUUIDv4() string` - 生成UUID Version 4 (随机) - `GenerateUUIDv1() string` - 生成UUID Version 1 (基于时间和MAC地址) - `GenerateSimpleUUID() string` - 生成简单UUID (无连字符) - `GenerateShortUUID() string` - 生成短UUID (22字符) **雪花ID (Snowflake)** - `GenerateSnowflakeID() int64` - 生成雪花ID (使用全局生成器) - `NewSnowflakeGenerator(workerID, datacenterID int64) (*SnowflakeGenerator, error)` - 创建自定义雪花ID生成器 - `ParseSnowflakeID(id int64) map[string]int64` - 解析雪花ID **短ID生成** - `GenerateShortID() string` - 生成短ID (8字符) - `GenerateShortIDWithLength(length int) string` - 生成指定长度的短ID - `GenerateNanoID(size int) string` - 生成NanoID风格的ID **ObjectID (MongoDB风格)** - `GenerateObjectID() string` - 生成ObjectID (MongoDB风格) - `ParseObjectID(objectID string) (map[string]interface{}, error)` - 解析ObjectID **业务专用ID** - `GenerateOrderID() string` - 生成订单ID (时间戳+随机数) - `GenerateTraceID() string` - 生成链路追踪ID - `GenerateSpanID() string` - 生成Span ID - `GenerateRequestID() string` - 生成请求ID - `GenerateSessionID() string` - 生成会话ID - `GenerateAPIKey() string` - 生成API密钥 - `GenerateSecretKey() string` - 生成密钥 **验证函数** - `ValidateUUID(uuid string) bool` - 验证UUID格式 - `ValidateObjectID(objectID string) bool` - 验证ObjectID格式 #### 使用示例 ```go import "gitee.com/ixgo/ixutils" // UUID生成 uuid := ixUtils.GenerateUUID() fmt.Println("UUID:", uuid) // UUID: 550e8400-e29b-41d4-a716-446655440000 // 雪花ID生成 snowflakeID := ixUtils.GenerateSnowflakeID() fmt.Println("雪花ID:", snowflakeID) // 雪花ID: 1234567890123456789 // 解析雪花ID parsed := ixUtils.ParseSnowflakeID(snowflakeID) fmt.Printf("解析结果: %+v\n", parsed) // 业务ID生成 orderID := ixUtils.GenerateOrderID() apiKey := ixUtils.GenerateAPIKey() fmt.Println("订单ID:", orderID) // 订单ID: 20230915143052123456 fmt.Println("API密钥:", apiKey) // API密钥: ak_1BvXerhVlMpXzRv4x2Nq8uY3Kw5Zr7tS ``` ### 🌐 网络工具 (net.go) 全面的网络处理工具,包含IP处理、网络检测、域名解析等功能。 #### 主要函数 **IP处理** - `GetLocalIP() string` - 获取本机内网IP地址 - `GetLocalIPs() []string` - 获取本机所有内网IP地址 - `GetPublicIP() string` - 获取公网IP地址 - `IsPrivateIP(ip string) bool` - 检查是否为私有IP地址 - `IsPublicIP(ip string) bool` - 检查是否为公网IP地址 - `IPToInt(ip string) uint32` - 将IP地址转换为32位无符号整数 - `IntToIP(ipInt uint32) string` - 将32位无符号整数转换为IP地址 - `IsValidIP(ip string) bool` - 检查IP地址格式是否有效 - `IsValidIPv4(ip string) bool` - 检查是否为有效的IPv4地址 - `IsValidIPv6(ip string) bool` - 检查是否为有效的IPv6地址 **网络检测** - `Ping(host string) bool` - 检测主机是否可达 - `PingWithTimeout(host string, timeout time.Duration) bool` - 带超时的Ping检测 - `IsPortOpen(host string, port int) bool` - 检查指定主机的端口是否开放 - `IsPortOpenWithTimeout(host, port, timeout) bool` - 带超时的端口检测 - `ScanPorts(host string, startPort, endPort int) []int` - 扫描主机的端口范围 - `ScanPortsWithTimeout(host, startPort, endPort, timeout) []int` - 带超时的端口扫描 **域名解析** - `GetDomainIP(domain string) []string` - 获取域名对应的IP地址列表 - `GetDomainIPWithTimeout(domain, timeout) []string` - 带超时的域名解析 - `GetDomainIPv4(domain string) []string` - 获取域名对应的IPv4地址列表 - `GetDomainIPv6(domain string) []string` - 获取域名对应的IPv6地址列表 **网络信息** - `GetMACAddress() string` - 获取本机MAC地址 - `GetAllMACAddresses() map[string]string` - 获取所有网络接口的MAC地址 - `GetNetworkInterfaces() []NetworkInterface` - 获取网络接口信息 **网络工具** - `IsValidPort(port int) bool` - 检查端口号是否有效 - `IsValidDomain(domain string) bool` - 检查域名格式是否有效 - `GetFreePort() (int, error)` - 获取一个可用的端口号 - `IsLocalhost(host string) bool` - 检查是否为本地地址 - `JoinHostPort(host string, port int) string` - 组合主机和端口 - `ParseHostPort(hostPort string) (host string, port int, err error)` - 解析主机和端口 **连接测试** - `TestTCPConnection(host string, port int) ConnectionTest` - 测试TCP连接 - `TestUDPConnection(host string, port int) ConnectionTest` - 测试UDP连接 - `BatchTestConnections(hosts []string, ports []int) []ConnectionTest` - 批量测试连接 #### 使用示例 ```go // IP处理 localIP := ixUtils.GetLocalIP() publicIP := ixUtils.GetPublicIP() fmt.Printf("本机IP: %s, 公网IP: %s\n", localIP, publicIP) // 网络检测 if ixUtils.Ping("www.baidu.com") { fmt.Println("网络连通") } if ixUtils.IsPortOpen("127.0.0.1", 3306) { fmt.Println("MySQL服务正在运行") } // 域名解析 ips := ixUtils.GetDomainIP("www.baidu.com") fmt.Println("百度IP地址:", ips) // 端口扫描 openPorts := ixUtils.ScanPorts("127.0.0.1", 20, 100) fmt.Println("开放端口:", openPorts) ``` ### 🔢 数学工具 (math.go) 全面的数学计算工具,支持基础数学运算、统计计算、数值处理等功能。 #### 主要函数 **基础数学运算** - `MaxInt(a, b int) int` / `Max[T](a, b T) T` - 返回最大值 - `MinInt(a, b int) int` / `Min[T](a, b T) T` - 返回最小值 - `AbsInt(n int) int` / `Abs[T](n T) T` - 返回绝对值 - `Round(f float64, precision int) float64` - 四舍五入到指定精度 - `Ceil(f float64) int` - 向上取整 - `Floor(f float64) int` - 向下取整 **数值处理** - `InRangeInt(value, min, max int) bool` / `InRange[T](value, min, max T) bool` - 检查是否在范围内 - `ClampInt(value, min, max int) int` / `Clamp[T](value, min, max T) T` - 限制在范围内 - `PercentageInt(part, total int) float64` / `Percentage[T](part, total T) float64` - 计算百分比 - `AverageInt(numbers []int) float64` / `Average[T](numbers []T) float64` - 计算平均值 **数组运算** - `SumInt(numbers []int) int` / `Sum[T](numbers []T) T` - 求和 - `MaxSliceInt(numbers []int) int` / `MaxSlice[T](numbers []T) T` - 数组最大值 - `MinSliceInt(numbers []int) int` / `MinSlice[T](numbers []T) T` - 数组最小值 **高级数学** - `PowerInt(base, exp int) int` - 整数幂运算 - `PowerFloat64(base, exp float64) float64` - 浮点数幂运算 - `Sqrt(f float64) float64` - 平方根 - `GCD(a, b int) int` - 最大公约数 - `LCM(a, b int) int` - 最小公倍数 **数值判断** - `IsEven(n int) bool` - 检查是否为偶数 - `IsOdd(n int) bool` - 检查是否为奇数 #### 使用示例 ```go // 基础数学运算 fmt.Println("最大值:", ixUtils.Max(10, 20)) // 20 fmt.Println("绝对值:", ixUtils.Abs(-15)) // 15 fmt.Println("四舍五入:", ixUtils.Round(3.14159, 2)) // 3.14 // 数值处理 fmt.Println("在范围内:", ixUtils.InRange(15, 10, 20)) // true fmt.Println("限制范围:", ixUtils.Clamp(25, 10, 20)) // 20 fmt.Println("百分比:", ixUtils.Percentage(25, 100)) // 25.0 // 数组运算 numbers := []int{10, 20, 30, 40, 50} fmt.Println("平均值:", ixUtils.Average(numbers)) // 30.0 fmt.Println("总和:", ixUtils.Sum(numbers)) // 150 fmt.Println("最大值:", ixUtils.MaxSlice(numbers)) // 50 ``` ### 🔤 字符串工具 (string.go) 强大的字符串处理工具,包含字符串格式化、命名转换、验证等功能。 #### 主要函数 **字符串格式化** - `PadLeft(str string, length int, pad string) string` - 左侧填充 - `PadRight(str string, length int, pad string) string` - 右侧填充 - `Truncate(str string, length int, suffix string) string` - 截断字符串 - `Capitalize(str string) string` - 首字母大写 - `LowerCase(str string) string` - 转小写 - `UpperCase(str string) string` - 转大写 **命名转换** - `CamelCase(str string) string` - 转驼峰命名 - `PascalCase(str string) string` - 转帕斯卡命名 - `SnakeCase(str string) string` - 转蛇形命名 - `KebabCase(str string) string` - 转短横线命名 - `TitleCase(str string) string` - 转标题格式 **字符串操作** - `Trim(str string) string` - 去除前后空格 - `TrimLeft(str, cutset string) string` - 去除左侧字符 - `TrimRight(str, cutset string) string` - 去除右侧字符 - `ReverseString(str string) string` - 反转字符串 - `Repeat(str string, count int) string` - 重复字符串 - `SplitMulti(str string, seps ...string) []string` - 按多个分隔符分割字符串 - `SplitRegex(str string, pattern string) ([]string, error)` - 按正则表达式分割字符串 - `Join(strs []string, sep string, prefix, suffix string) string` - 连接字符串(支持前缀后缀) - `Substring(str string, start, end int) string` - 获取字符串子串(按字符位置) - `SubstringByBytes(str string, start, end int) string` - 获取字符串子串(按字节位置) - `ReplaceFirst(str, old, new string) string` - 替换第一个匹配的子字符串 - `ReplaceLast(str, old, new string) string` - 替换最后一个匹配的子字符串 - `ReplaceN(str, old, new string, n int) string` - 替换前n个匹配的子字符串 - `RemoveSubstring(str, substr string) string` - 移除字符串中所有出现的指定子字符串 - `RemoveRegex(str, pattern string) (string, error)` - 使用正则表达式移除匹配的子字符串 **字符串脱敏** - `Mask(str string, keepStart, keepEnd int, maskChar rune) string` - 字符串脱敏(默认保留前3后4位) - `MaskPhone(phone string) string` - 手机号脱敏(保留前3后4位) - `MaskEmail(email string) string` - 邮箱脱敏(保留@前2位和@后所有字符) - `MaskIDCard(idCard string) string` - 身份证号脱敏(保留前6后4位) - `MaskBankCard(bankCard string) string` - 银行卡号脱敏(保留前4后4位) **字符串提取** - `ExtractNumbers(str string) string` - 提取字符串中的数字 - `ExtractLetters(str string) string` - 提取字符串中的字母 - `ExtractAlphaNumeric(str string) string` - 提取字符串中的字母和数字 - `ExtractRegex(str, pattern string) ([]string, error)` - 使用正则表达式提取字符串 **字符串统计** - `CountOccurrences(str, substr string) int` - 统计子字符串出现的次数 - `CountOccurrencesRegex(str, pattern string) (int, error)` - 使用正则表达式统计匹配次数 - `CountCharacters(str string) int` - 统计字符串中的字符数量(按rune计算) - `CountWords(str string) int` - 统计字符串中的单词数量(以空格分隔) **字符串判断** - `IsBlank(str string) bool` - 是否为空白字符串 - `IsNotEmpty(str string) bool` - 是否非空 - `IsNotBlank(str string) bool` - 是否非空白 - `ContainsAll(str string, substrs ...string) bool` - 检查字符串是否包含所有指定的子字符串 - `ContainsAny(str string, substrs ...string) bool` - 检查字符串是否包含任意一个指定的子字符串 **字符串验证** - `IsEmail(str string) bool` - 验证邮箱格式 - `IsPhone(str string) bool` - 验证手机号 - `IsURL(str string) bool` - 验证URL格式 - `IsIP(str string) bool` - 验证IP地址 - `IsIPv4(str string) bool` - 验证IPv4地址 - `IsIPv6(str string) bool` - 验证IPv6地址 - `IsNumeric(str string) bool` - 验证是否为数字 - `IsInteger(str string) bool` - 验证是否为整数 - `IsFloat(str string) bool` - 验证是否为浮点数 - `IsAlpha(str string) bool` - 验证是否为字母 - `IsAlphaNumeric(str string) bool` - 验证是否为字母数字 #### 使用示例 ```go // 字符串格式化 fmt.Println("左填充:", ixUtils.PadLeft("123", 5, "0")) // 00123 fmt.Println("截断:", ixUtils.Truncate("Hello World", 5, "...")) // Hello... fmt.Println("首字母大写:", ixUtils.Capitalize("hello")) // Hello // 命名转换 fmt.Println("驼峰命名:", ixUtils.CamelCase("hello_world")) // helloWorld fmt.Println("蛇形命名:", ixUtils.SnakeCase("HelloWorld")) // hello_world fmt.Println("短横线:", ixUtils.KebabCase("HelloWorld")) // hello-world // 字符串验证 fmt.Println("邮箱验证:", ixUtils.IsEmail("test@example.com")) // true fmt.Println("手机验证:", ixUtils.IsPhone("13800138000")) // true fmt.Println("数字验证:", ixUtils.IsNumeric("12345")) // true ``` ### 🔢 版本比较 (ver.go) 版本号比较工具,支持语义化版本号的大小比较。 #### 主要函数 - `CompareVersion(v1, v2 string) int` - 比较两个版本号大小 #### 使用示例 ```go // 版本号比较 result := ixUtils.CompareVersion("1.2.3", "1.2.4") // result = -1 (1.2.3 < 1.2.4) result = ixUtils.CompareVersion("2.0.0", "1.9.9") // result = 1 (2.0.0 > 1.9.9) result = ixUtils.CompareVersion("1.0.0", "1.0.0") // result = 0 (1.0.0 = 1.0.0) // 支持v前缀和预发布版本 result = ixUtils.CompareVersion("v1.2.3", "v1.2.4") // -1 result = ixUtils.CompareVersion("1.2", "1.2.0") // 0 ``` ### 📊 数组工具 (array.go) 强大的数组处理工具,使用Go泛型提供类型安全的数组操作。 #### 主要函数 **基础操作** - `Contains[T comparable](arr []T, v T) bool` - 检查数组是否包含指定元素 - `IndexOf[T comparable](arr []T, v T) int` - 查找元素在数组中的索引 - `Remove[T comparable](arr []T, v T) []T` - 从数组中移除指定元素 - `Reverse[T any](arr []T) []T` - 反转数组 **数组处理** - `Unique[T comparable](arr []T) []T` - 去除数组中的重复元素 - `Filter[T any](arr []T, f func(T) bool) []T` - 过滤数组元素 - `Map[T any, R any](arr []T, f func(T) R) []R` - 映射数组元素 - `Concat[T any](slices ...[]T) []T` - 连接多个数组 **条件判断** - `Any[T any](arr []T, f func(T) bool) bool` - 检查是否有任何元素满足条件 - `All[T any](arr []T, f func(T) bool) bool` - 检查是否所有元素都满足条件 **集合操作** - `Union[T comparable](a, b []T) []T` - 数组并集 - `Intersect[T comparable](a, b []T) []T` - 数组交集 - `Difference[T comparable](a, b []T) []T` - 数组差集 **数组增强功能** - `Chunk[T any](arr []T, size int) [][]T` - 将切片按指定大小分块 - `Flatten[T any](arr [][]T) []T` - 扁平化嵌套切片 - `GroupBy[T any, K comparable](arr []T, keyFunc func(T) K) map[K][]T` - 按条件分组 - `Sort[T interface{...}](arr []T, ascending bool) []T` - 排序切片(适用于可排序类型) - `SortBy[T any](arr []T, lessFunc func(T, T) bool) []T` - 按条件排序 - `SortByKey[T any, K interface{...}](arr []T, keyFunc func(T) K, ascending bool) []T` - 按提取的键排序 - `Partition[T any](arr []T, predicate func(T) bool) ([]T, []T)` - 按条件分区 - `Zip[T any](slices ...[]T) [][]T` - 组合多个切片(长度取最短的) - `Unzip[T any](zipped [][]T) [][]T` - 解组切片 - `Batch[T any](arr []T, batchSize int, batchFunc func([]T) error) error` - 批量处理 - `Take[T any](arr []T, n int) []T` - 取前n个元素 - `Drop[T any](arr []T, n int) []T` - 丢弃前n个元素 - `TakeWhile[T any](arr []T, predicate func(T) bool) []T` - 取满足条件的连续元素 - `DropWhile[T any](arr []T, predicate func(T) bool) []T` - 丢弃满足条件的连续元素 - `Distinct[T comparable](arr []T) []T` - 去重(保持顺序) - `Compact[T comparable](arr []T) []T` - 移除零值元素 - `First[T any](arr []T) (T, bool)` - 获取第一个元素 - `Last[T any](arr []T) (T, bool)` - 获取最后一个元素 - `Reduce[T any, R any](arr []T, initial R, reducer func(R, T) R) R` - 归约操作 #### 使用示例 ```go // 基础操作 numbers := []int{1, 2, 3, 4, 5} fmt.Println("包含3:", ixUtils.Contains(numbers, 3)) // true fmt.Println("3的索引:", ixUtils.IndexOf(numbers, 3)) // 2 fmt.Println("移除3:", ixUtils.Remove(numbers, 3)) // [1, 2, 4, 5] // 数组处理 duplicates := []int{1, 2, 2, 3, 3, 4} fmt.Println("去重:", ixUtils.Unique(duplicates)) // [1, 2, 3, 4] evens := ixUtils.Filter(numbers, func(n int) bool { return n%2 == 0 }) fmt.Println("偶数:", evens) // [2, 4] doubled := ixUtils.Map(numbers, func(n int) int { return n * 2 }) fmt.Println("翻倍:", doubled) // [2, 4, 6, 8, 10] // 集合操作 a := []int{1, 2, 3} b := []int{3, 4, 5} fmt.Println("并集:", ixUtils.Union(a, b)) // [1, 2, 3, 4, 5] fmt.Println("交集:", ixUtils.Intersect(a, b)) // [3] fmt.Println("差集:", ixUtils.Difference(a, b)) // [1, 2] ``` ### 🏗️ 结构体工具 (struct.go) 全面的结构体操作工具,支持结构体与Map的相互转换、字段操作等。 #### 主要函数 **基础转换** - `StructToMap(obj interface{}) (map[string]interface{}, error)` - 结构体转Map - `MapToStruct(data map[string]interface{}, result interface{}) error` - Map转结构体 - `StructToMapWithTag(obj interface{}, tagName string) (map[string]interface{}, error)` - 使用指定tag转换 - `MapToStructWithTag(data map[string]interface{}, result interface{}, tagName string) error` - 使用指定tag转换 **字段操作** - `GetStructFields(obj interface{}) []string` - 获取结构体字段名列表 - `GetStructTags(obj interface{}, tagName string) map[string]string` - 获取结构体标签 - `GetStructFieldValue(obj interface{}, fieldName string) (interface{}, error)` - 获取字段值 - `SetStructFieldValue(obj interface{}, fieldName string, value interface{}) error` - 设置字段值 - `HasStructField(obj interface{}, fieldName string) bool` - 检查是否有指定字段 - `GetStructFieldType(obj interface{}, fieldName string) (reflect.Type, error)` - 获取字段类型 **JSON转换** - `StructToJson(obj interface{}) (string, error)` - 结构体转JSON - `JsonToStruct(data string, result interface{}) error` - JSON转结构体 **结构体复制** - `CopyStruct(src, dst interface{}) error` - 复制结构体 **强制转换版本 (Must系列)** - `MustStructToMap(obj interface{}) map[string]interface{}` - 强制结构体转Map - `MustMapToStruct(data map[string]interface{}, result interface{})` - 强制Map转结构体 - `MustGetStructFieldValue(obj interface{}, fieldName string) interface{}` - 强制获取字段值 - `MustSetStructFieldValue(obj interface{}, fieldName string, value interface{})` - 强制设置字段值 - `MustStructToJson(obj interface{}) string` - 强制结构体转JSON - 等等... #### 使用示例 ```go type User struct { Name string `json:"name" db:"user_name"` Age int `json:"age" db:"user_age"` Email string `json:"email" db:"user_email"` } user := User{Name: "张三", Age: 25, Email: "zhangsan@example.com"} // 结构体转Map userMap, err := ixUtils.StructToMap(user) fmt.Printf("用户Map: %+v\n", userMap) // 使用指定tag转换 dbMap, err := ixUtils.StructToMapWithTag(user, "db") fmt.Printf("数据库Map: %+v\n", dbMap) // 获取字段信息 fields := ixUtils.GetStructFields(user) fmt.Println("字段列表:", fields) // 获取字段值 name, err := ixUtils.GetStructFieldValue(user, "Name") fmt.Println("姓名:", name) // 强制转换 (不返回错误) userMap2 := ixUtils.MustStructToMap(user) fmt.Printf("强制转换: %+v\n", userMap2) ``` ### 🗺️ Map工具 (map.go) 强大的Map处理工具,提供Map操作、转换等功能。 #### 主要函数 **基础操作** - `MapKeys[K comparable, V any](m map[K]V) []K` - 获取Map的所有键 - `MapValues[K comparable, V any](m map[K]V) []V` - 获取Map的所有值 - `MapContains[K comparable, V any](m map[K]V, key K) bool` - 检查Map是否包含指定的键 - `MapGet[K comparable, V any](m map[K]V, key K, defaultValue V) V` - 获取Map的值,如果不存在返回默认值 - `MapSet[K comparable, V any](m map[K]V, key K, value V)` - 设置Map的值 - `MapDelete[K comparable, V any](m map[K]V, key K)` - 删除Map中的键 - `MapClear[K comparable, V any](m map[K]V)` - 清空Map - `MapSize[K comparable, V any](m map[K]V) int` - 获取Map的大小 - `MapIsEmpty[K comparable, V any](m map[K]V) bool` - 检查Map是否为空 - `MapClone[K comparable, V any](m map[K]V) map[K]V` - 克隆Map(浅拷贝) **Map处理** - `MapFilter[K comparable, V any](m map[K]V, predicate func(K, V) bool) map[K]V` - 过滤Map - `MapMap[K comparable, V any, R any](m map[K]V, mapper func(K, V) R) map[K]R` - 映射Map的值 - `MapMerge[K comparable, V any](maps ...map[K]V) map[K]V` - 合并多个Map - `MapAny[K comparable, V any](m map[K]V, predicate func(K, V) bool) bool` - 判断Map中是否有元素满足条件 - `MapAll[K comparable, V any](m map[K]V, predicate func(K, V) bool) bool` - 判断Map中是否所有元素都满足条件 - `MapReduce[K comparable, V any, R any](m map[K]V, initial R, reducer func(R, K, V) R) R` - 归约Map **Map转换** - `MapToSlice[K comparable, V any](m map[K]V) []Pair[K, V]` - 将Map转换为键值对切片 - `SliceToMap[K comparable, V any](pairs []Pair[K, V]) map[K]V` - 将键值对切片转换为Map - `MapFromSlices[K comparable, V any](keys []K, values []V) map[K]V` - 从键切片和值切片创建Map - `MapKeyBy[T any, K comparable](arr []T, keyFunc func(T) K) map[K]T` - 从切片创建Map,使用指定函数提取键 - `MapGroupBy[T any, K comparable](arr []T, keyFunc func(T) K) map[K][]T` - 按条件分组(返回Map) #### 使用示例 ```go userMap := map[string]int{ "Alice": 25, "Bob": 30, "Carol": 28, } // 基础操作 keys := ixUtils.MapKeys(userMap) fmt.Println("键:", keys) // [Alice Bob Carol] values := ixUtils.MapValues(userMap) fmt.Println("值:", values) // [25 30 28] // Map处理 filtered := ixUtils.MapFilter(userMap, func(k string, v int) bool { return v > 26 }) fmt.Println("过滤后:", filtered) // map[Bob:30 Carol:28] mapped := ixUtils.MapMap(userMap, func(k string, v int) string { return fmt.Sprintf("%s:%d", k, v) }) fmt.Println("映射后:", mapped) // map[Alice:Alice:25 ...] // Map转换 pairs := ixUtils.MapToSlice(userMap) fmt.Println("键值对:", pairs) // [{Alice 25} {Bob 30} {Carol 28}] // 从切片创建Map users := []string{"Alice", "Bob", "Carol"} userMap2 := ixUtils.MapKeyBy(users, func(s string) string { return s }) fmt.Println("从切片创建:", userMap2) // map[Alice:Alice Bob:Bob Carol:Carol] ``` ### 📄 JSON工具 (json.go) 完整的JSON处理工具,支持编码、解码、文件操作、流处理等。 #### 主要函数 **基础JSON操作** - `JsonEncode(v interface{}) (string, error)` - JSON编码 - `JsonEncodePretty(v interface{}) (string, error)` - 格式化JSON编码 - `JsonDecode(data string, v interface{}) error` - JSON解码 - `IsValidJson(str string) bool` - 验证JSON格式 **文件操作** - `JsonEncodeFile(v interface{}, filename string) error` - 编码到文件 - `JsonDecodeFile(filename string, v interface{}) error` - 从文件解码 **流操作** - `JsonEncodeStream(v interface{}, w io.Writer) error` - 流编码 - `JsonDecodeStream(r io.Reader, v interface{}) error` - 流解码 **JSON操作** - `JsonGetField(data string, field string) (interface{}, error)` - 获取JSON字段 - `JsonSetField(data string, field string, value interface{}) (string, error)` - 设置JSON字段 - `JsonMerge(json1, json2 string) (string, error)` - 合并JSON **强制转换版本 (Must系列)** - `MustJsonEncode(v interface{}) string` - 强制JSON编码 - `MustJsonEncodePretty(v interface{}) string` - 强制格式化编码 - `MustJsonDecode(data string, v interface{})` - 强制JSON解码 - 等等... #### 使用示例 ```go user := map[string]interface{}{ "name": "张三", "age": 25, "email": "zhangsan@example.com", } // JSON编码 jsonStr, err := ixUtils.JsonEncode(user) fmt.Println("JSON:", jsonStr) // 格式化编码 prettyJson, err := ixUtils.JsonEncodePretty(user) fmt.Println("格式化JSON:", prettyJson) // JSON解码 var result map[string]interface{} err = ixUtils.JsonDecode(jsonStr, &result) // JSON验证 fmt.Println("有效JSON:", ixUtils.IsValidJson(jsonStr)) // true // 强制编码 (不返回错误) jsonStr2 := ixUtils.MustJsonEncode(user) fmt.Println("强制编码:", jsonStr2) ``` ### 🔄 类型转换 (convert.go) 强大的类型转换工具,支持字符串、数字、布尔值等类型之间的相互转换。 #### 主要函数 **基础转换** - `ToInt(v interface{}) (int, error)` - 将任意类型转换为int - `ToInt64(v interface{}) (int64, error)` - 将任意类型转换为int64 - `ToFloat(v interface{}) (float64, error)` - 将任意类型转换为float64 - `ToBool(v interface{}) (bool, error)` - 将任意类型转换为bool - `ToStr(v interface{}) string` - 将任意类型转换为字符串 **强制转换版本 (Must系列)** - `MustInt(v interface{}) int` - 强制转换为int,失败返回默认值 - `MustInt64(v interface{}) int64` - 强制转换为int64,失败返回默认值 - `MustFloat(v interface{}) float64` - 强制转换为float64,失败返回默认值 - `MustBool(v interface{}) bool` - 强制转换为bool,失败返回默认值 **通用转换** - `ToType(v interface{}, targetType string) (interface{}, error)` - 转换为指定类型 - `MustType(v interface{}, targetType string) interface{}` - 强制转换为指定类型 **辅助函数** - `IsNil(v interface{}) bool` - 检查值是否为nil - `IsEmpty(v interface{}) bool` - 检查值是否为空(nil、空字符串、0、false等) #### 使用示例 ```go // 基础转换 num, err := ixUtils.ToInt("123") fmt.Println("转换为整数:", num) // 123 // 强制转换 (带默认值) num2 := ixUtils.MustInt("abc") fmt.Println("强制转换:", num2) // 0 (转换失败使用默认值) // 字符串转换 str := ixUtils.ToStr(456) fmt.Println("转换为字符串:", str) // "456" // 类型转换 value, err := ixUtils.ToType("789", "int64") fmt.Println("转换为int64:", value) // 789 // 空值检查 fmt.Println("是否为空:", ixUtils.IsEmpty("")) // true fmt.Println("是否为空:", ixUtils.IsEmpty(0)) // true ``` ### ❌ 错误处理工具 (error.go) 强大的错误处理工具,包含错误包装、错误判断、错误重试等功能。 #### 主要函数 **错误包装** - `WrapError(err error, message string) error` - 包装错误,添加上下文信息 - `WrapErrorf(err error, format string, args ...interface{}) error` - 包装错误,使用格式化字符串 - `UnwrapError(err error) error` - 解包错误,获取原始错误 - `UnwrapAllErrors(err error) []error` - 解包所有错误,返回错误链 **错误判断** - `IsError(err, target error) bool` - 检查错误是否为指定类型 - `AsError(err error, target interface{}) bool` - 检查错误是否可以转换为指定类型 - `IsErrorOf(err error, errType interface{}) bool` - 检查错误是否为指定错误类型 - `IsErrorTimeout(err error) bool` - 检查是否为超时错误(通过错误消息判断) - `IsErrorNetwork(err error) bool` - 检查是否为网络错误(通过错误消息判断) **错误合并** - `CombineErrors(errs ...error) error` - 合并多个错误为一个错误 - `CombineErrorsWithSeparator(errs []error, separator string) error` - 合并多个错误,使用指定分隔符 **错误重试** - `Retry(fn func() error, config ...RetryConfig) error` - 重试执行函数,直到成功或达到最大重试次数 - `RetryWithResult[T any](fn func() (T, error), config ...RetryConfig) (T, error)` - 重试执行函数并返回结果 - `RetryUntil(fn func() error, condition func(error) bool, timeout time.Duration) error` - 重试执行函数,直到满足条件或超时 **错误信息** - `ErrorMessage(err error) string` - 获取错误消息 - `ErrorStack(err error) []string` - 获取错误堆栈(错误链) - `ErrorCause(err error) error` - 获取错误的根原因 #### 使用示例 ```go // 错误包装 err := errors.New("原始错误") wrapped := ixUtils.WrapError(err, "处理用户数据时") fmt.Println(wrapped.Error()) // 处理用户数据时: 原始错误 // 错误重试 config := ixUtils.RetryConfig{ MaxAttempts: 3, Delay: time.Second, Backoff: 1.5, OnRetry: func(attempt int, err error) { fmt.Printf("第%d次重试,错误: %v\n", attempt, err) }, } err = ixUtils.Retry(func() error { // 执行可能失败的操作 return someOperation() }, config) // 错误合并 err1 := errors.New("错误1") err2 := errors.New("错误2") combined := ixUtils.CombineErrors(err1, err2) fmt.Println(combined.Error()) // 错误1; 错误2 // 错误堆栈 stack := ixUtils.ErrorStack(wrapped) fmt.Println("错误堆栈:", stack) // [处理用户数据时: 原始错误 原始错误] ``` ### ✅ 验证工具 (validator.go) 全面的验证工具,包含身份证、银行卡、中文姓名等验证功能。 #### 主要函数 **身份证验证** - `IsIDCard(idCard string) bool` - 验证身份证号(支持15位和18位) - `ParseIDCard(idCard string) map[string]interface{}` - 解析身份证信息(出生日期、性别、地区等) **银行卡验证** - `IsBankCard(cardNumber string) bool` - 验证银行卡号(使用Luhn算法) - `IsCreditCard(cardNumber string) bool` - 验证信用卡号(别名,使用银行卡验证) **中文姓名验证** - `IsChineseName(name string) bool` - 验证中文姓名 - `IsChineseNameStrict(name string) bool` - 严格验证中文姓名(只允许中文和·) **URL参数验证** - `ValidateURLParams(params map[string]string, rules map[string]string) (bool, map[string]string)` - 验证URL参数 **其他验证** - `IsPassport(passport string) bool` - 验证护照号 - `IsSocialSecurityNumber(ssn string) bool` - 验证社会保障号 #### 使用示例 ```go // 身份证验证 idCard := "110101199001011234" if ixUtils.IsIDCard(idCard) { info := ixUtils.ParseIDCard(idCard) fmt.Println("出生年份:", info["birthYear"]) // 1990 fmt.Println("性别:", info["gender"]) // 男 } // 中文姓名验证 name := "张三" fmt.Println("是否有效:", ixUtils.IsChineseName(name)) // true // URL参数验证 params := map[string]string{ "email": "test@example.com", "age": "25", } rules := map[string]string{ "email": "required,email", "age": "required,numeric,min:1,max:120", } valid, errors := ixUtils.ValidateURLParams(params, rules) if !valid { fmt.Println("验证错误:", errors) } ``` ### 🔀 三元运算 (ternary.go) 提供三元运算符和空值合并等便捷函数。 #### 主要函数 - `Ternary[T any](cond bool, a, b T) T` - 三元运算符,条件为true返回a,否则返回b - `Coalesce[T comparable](values ...T) T` - 返回第一个非零值 - `IfErr[T any](err error, a, b T) T` - error不为nil返回b,否则返回a - `Default[T comparable](v, def T) T` - 如果v为零值则返回def,否则返回v - `PtrOrVal[T any](ptr *T, def T) T` - 指针不为nil返回指针指向的值,否则返回默认值 #### 使用示例 ```go // 三元运算符 result := ixUtils.Ternary(10 > 5, "大于", "小于等于") fmt.Println(result) // "大于" // 空值合并 str := ixUtils.Coalesce("", "默认值", "其他") fmt.Println(str) // "默认值" // 错误处理 data, err := someFunction() result2 := ixUtils.IfErr(err, data, nil) fmt.Println(result2) // 默认值 value := ixUtils.Default("", "默认值") fmt.Println(value) // "默认值" // 指针处理 var ptr *int num := ixUtils.PtrOrVal(ptr, 10) fmt.Println(num) // 10 ``` ### 🌐 HTTP工具 (http.go) 全面的HTTP请求工具,支持GET、POST、PUT、DELETE等各种HTTP方法,以及文件上传、Cookie管理等功能。 #### 主要函数 **基础HTTP请求** - `Get(url string, config ...*HttpConfig) (*http.Response, error)` - GET请求 - `Post(url string, args ...interface{}) (*http.Response, error)` - POST请求 - `Put(url string, args ...interface{}) (*http.Response, error)` - PUT请求 - `Delete(url string, config ...*HttpConfig) (*http.Response, error)` - DELETE请求 - `Patch(url string, args ...interface{}) (*http.Response, error)` - PATCH请求 - `HttpRequest(method, url string, body interface{}, config *HttpConfig) (*http.Response, error)` - 通用HTTP请求 **响应处理** - `ReadResponse(resp *http.Response) ([]byte, error)` - 读取响应内容 - `ReadResponseString(resp *http.Response) (string, error)` - 读取响应内容为字符串 - `ReadResponseJson(resp *http.Response, v interface{}) error` - 读取响应内容为JSON **文件上传** - `UploadFile(url string, fieldName, filePath string, extraFields map[string]string, config *HttpConfig) (*http.Response, error)` - 文件上传 **Cookie处理** - `GetCookies(resp *http.Response) []*http.Cookie` - 获取响应中的Cookie - `GetCookie(resp *http.Response, name string) *http.Cookie` - 获取指定名称的Cookie **URL处理** - `BuildUrl(baseUrl string, params map[string]string) string` - 构建URL - `ParseUrl(urlStr string) (*url.URL, error)` - 解析URL **客户端管理** - `NewHttpClient(config *HttpConfig) (*http.Client, error)` - 创建HTTP客户端 #### 使用示例 ```go // 基础GET请求 resp, err := ixUtils.Get("https://api.example.com/users") if err == nil { body, _ := ixUtils.ReadResponseString(resp) fmt.Println("响应内容:", body) } // POST请求发送JSON data := map[string]interface{}{ "name": "张三", "age": 25, } resp, err = ixUtils.Post("https://api.example.com/users", data) // 自定义配置 config := &ixUtils.HttpConfig{ Timeout: 30 * time.Second, Headers: map[string]string{ "Authorization": "Bearer token123", "Content-Type": "application/json", }, } resp, err = ixUtils.Get("https://api.example.com/protected", config) // 文件上传 extraFields := map[string]string{"description": "test"} resp, err = ixUtils.UploadFile("https://api.example.com/upload", "file", "/path/to/file.jpg", extraFields, config) // 读取JSON响应 var result map[string]interface{} err = ixUtils.ReadResponseJson(resp, &result) ``` ### 🔐 加密工具 (crypto.go) 全面的加密和编码工具,支持MD5、SHA系列、HMAC、Base64、Hex等多种加密和编码方式。 #### 主要函数 **MD5加密** - `MD5(str string) string` - 计算字符串的MD5值 - `MD5Bytes(data []byte) string` - 计算字节数组的MD5值 - `MD5File(filePath string) (string, error)` - 计算文件的MD5值 **SHA系列加密** - `SHA1(str string) string` - 计算字符串的SHA1值 - `SHA1Bytes(data []byte) string` - 计算字节数组的SHA1值 - `SHA256(str string) string` - 计算字符串的SHA256值 - `SHA256Bytes(data []byte) string` - 计算字节数组的SHA256值 - `SHA512(str string) string` - 计算字符串的SHA512值 - `SHA512Bytes(data []byte) string` - 计算字节数组的SHA512值 **HMAC加密** - `HMACMD5(key, str string) string` - HMAC-MD5加密 - `HMACSHA1(key, str string) string` - HMAC-SHA1加密 - `HMACSHA256(key, str string) string` - HMAC-SHA256加密 - `HMACSHA512(key, str string) string` - HMAC-SHA512加密 **对称与非对称加密** - `AESEncrypt(plaintext, key []byte) ([]byte, error)` - AES-GCM 高阶加密 - `AESDecrypt(ciphertext, key []byte) ([]byte, error)` - AES-GCM 高阶解密 - `GenerateRSAKeyPair(bits int) ([]byte, []byte, error)` - 生成 RSA 公私钥 - `RSAEncrypt(plaintext, publicKeyPEM []byte) ([]byte, error)` - RSA 公钥加密 - `RSADecrypt(ciphertext, privateKeyPEM []byte) ([]byte, error)` - RSA 私钥解密 - `RSASign(data, privateKeyPEM []byte) ([]byte, error)` - RSA 签名 (SHA256) - `RSAVerify(data, signature, publicKeyPEM []byte) error` - RSA 验签 (SHA256) **密码处理** - `PasswordHash(password string) string` - 密码哈希(使用SHA256) - `PasswordVerify(password, hash string) bool` - 密码验证 **Base64编码** - `Base64Encode(str string) string` - Base64编码 - `Base64Decode(str string) (string, error)` - Base64解码 - `Base64UrlEncode(str string) string` - Base64 URL安全编码 - `Base64UrlDecode(str string) (string, error)` - Base64 URL安全解码 **Hex编码** - `HexEncode(str string) string` - Hex编码 - `HexDecode(str string) (string, error)` - Hex解码 #### 使用示例 ```go text := "Hello, World!" // MD5加密 md5Hash := ixUtils.MD5(text) fmt.Println("MD5:", md5Hash) // SHA256加密 sha256Hash := ixUtils.SHA256(text) fmt.Println("SHA256:", sha256Hash) // HMAC-SHA256加密 key := "secret-key" hmacHash := ixUtils.HmacSHA256(text, key) fmt.Println("HMAC-SHA256:", hmacHash) // Base64编码 encoded := ixUtils.Base64Encode(text) fmt.Println("Base64编码:", encoded) decoded, err := ixUtils.Base64Decode(encoded) if err == nil { fmt.Println("Base64解码:", decoded) } // 文件MD5 fileMD5, err := ixUtils.MD5File("/path/to/file.txt") if err == nil { fmt.Println("文件MD5:", fileMD5) } ``` ### 🎲 随机数工具 (random.go) 强大的随机数生成工具,支持随机整数、随机字符串、随机数组等功能。 #### 主要函数 **随机数生成** - `RandomInt(min, max int) int` - 生成指定范围的随机整数 - `RandomInt64(min, max int64) int64` - 生成指定范围的随机64位整数 - `RandomFloat64(min, max float64) float64` - 生成指定范围的随机浮点数 **随机字符串** - `RandomString(n int) string` - 生成指定长度的随机字符串 - `RandomNumberString(n int) string` - 生成指定长度的随机数字字符串 - `RandomSpecialString(n int) string` - 生成指定长度的随机特殊字符字符串 **随机字节** - `RandomBytes(n int) []byte` - 生成指定长度的随机字节数组 **随机选择** - `RandomElement[T any](slice []T) T` - 从切片中随机选择一个元素 - `RandomElements[T any](slice []T, n int) []T` - 从切片中随机选择n个元素 **随机布尔和概率** - `RandomBool() bool` - 生成随机布尔值 - `RandomWeight(weights []float64) int` - 根据权重随机选择 **数组打乱** - `Shuffle[T any](slice []T)` - 打乱数组顺序(原地) **随机时间** - `RandomTime(start, end time.Time) time.Time` - 生成指定时间范围内的随机时间 #### 使用示例 ```go // 随机数生成 randomNum := ixUtils.RandomInt(1, 100) fmt.Println("随机数:", randomNum) // 随机字符串 randomStr := ixUtils.RandomString(10) fmt.Println("随机字符串:", randomStr) // 自定义字符集 customStr := ixUtils.RandomStringWithCharset(8, "ABCDEF0123456789") fmt.Println("自定义字符串:", customStr) // 随机选择 fruits := []string{"苹果", "香蕉", "橙子", "葡萄"} randomFruit := ixUtils.RandomChoice(fruits) fmt.Println("随机水果:", randomFruit) // 随机采样 samples := ixUtils.RandomSample(fruits, 2) fmt.Println("随机采样:", samples) // 数组打乱 numbers := []int{1, 2, 3, 4, 5} shuffled := ixUtils.Shuffle(numbers) fmt.Println("打乱后:", shuffled) ``` ### 🔄 并发工具 (concurrent.go) 强大的并发控制工具,提供增强版的WaitGroup、工作池、并发限制等功能。 #### 主要函数 **增强WaitGroup** - `NewWaitGroup(ctx context.Context, timeout time.Duration) *WaitGroup` - 创建支持超时和取消的WaitGroup - `Add(delta int)` - 添加等待计数 - `Done()` - 完成一个任务 - `Wait() error` - 等待所有任务完成,支持超时和取消 **工作池** - `NewPool(workers int) *Pool` - 创建工作池 - `Start()` - 启动协程池 - `Submit(task func()) error` - 提交任务 - `Stop()` - 停止协程池 **原子操作** - `NewAtomicBool(initial bool) *AtomicBool` - 创建原子布尔值 - `NewAtomicInt64(initial int64) *AtomicInt64` - 创建原子整数 - `Set(value)` / `Get()` / `Add(delta)` - 原子操作 **增强Once** - `NewOnce() *Once` - 创建增强版Once - `Do(f func())` - 执行函数,确保只执行一次 - `Reset()` - 重置Once,允许再次执行 **增强Mutex** - `NewMutex(timeout time.Duration) *Mutex` - 创建支持超时的互斥锁 - `Lock() error` / `Unlock()` - 加锁/解锁 - `NewRWMutex(timeout time.Duration) *RWMutex` - 创建支持超时的读写锁 - `Lock()` / `RLock()` / `Unlock()` / `RUnlock()` - 读写锁操作 **信号量和屏障** - `NewSemaphore(size int) *Semaphore` - 创建信号量 - `Acquire()` / `Release()` / `TryAcquire(timeout)` - 信号量操作 - `NewBarrier(parties int, timeout time.Duration) *Barrier` - 创建屏障 - `Await() (int, error)` - 等待所有线程到达屏障 #### 使用示例 ```go // 使用增强WaitGroup ctx := context.Background() wg := ixUtils.NewWaitGroup(ctx, 30*time.Second) for i := 0; i < 5; i++ { wg.Add(1) go func(id int) { defer wg.Done() time.Sleep(time.Second) fmt.Printf("任务 %d 完成\n", id) }(i) } err := wg.Wait() if err != nil { fmt.Println("等待超时或被取消") } // 使用工作池 pool := ixUtils.NewPool(3) pool.Start() defer pool.Stop() for i := 0; i < 10; i++ { taskID := i pool.Submit(func() { fmt.Printf("执行任务 %d\n", taskID) }) } // 使用信号量限制并发 sem := ixUtils.NewSemaphore(2) // 最多2个并发 sem.Acquire() defer sem.Release() ``` ### 📁 文件工具 (file.go) 全面的文件操作工具,支持文件读写、目录操作、文件信息获取等功能。 #### 主要函数 **文件检查** - `FileExists(path string) bool` - 检查文件是否存在 - `IsDir(path string) bool` - 检查路径是否为目录 - `IsFile(path string) bool` - 检查路径是否为文件 - `FileSize(path string) (int64, error)` - 获取文件大小 - `FileModTime(path string) (time.Time, error)` - 获取文件修改时间 - `FileMode(path string) (os.FileMode, error)` - 获取文件权限模式 **文件读写** - `ReadFile(path string) ([]byte, error)` - 读取文件内容(字节) - `ReadFileString(path string) (string, error)` - 读取文件内容(字符串) - `WriteFile(path string, data []byte) error` - 写入文件内容(字节) - `WriteFileString(path string, content string) error` - 写入文件内容(字符串) - `AppendFile(path string, data []byte) error` - 追加文件内容(字节) - `AppendFileString(path string, content string) error` - 追加文件内容(字符串) **文件操作** - `CopyFile(src, dst string) error` - 复制文件 - `MoveFile(src, dst string) error` - 移动文件 - `DeleteFile(path string) error` - 删除文件 - `CreateDir(path string) error` - 创建目录 - `DeleteDir(path string) error` - 删除目录 **文件信息** - `GetFileExt(path string) string` - 获取文件扩展名 - `GetFileName(path string) string` - 获取文件名(不含扩展名) - `GetFilePath(path string) string` - 获取文件所在目录 **目录遍历** - `ListDir(path string) ([]string, error)` - 列出目录内容 - `ListDirRecursive(path string) ([]string, error)` - 递归列出目录内容 **文件读写(按行)** - `ReadFileLines(path string) ([]string, error)` - 按行读取文件 - `WriteFileLines(path string, lines []string) error` - 按行写入文件 **文件压缩提取打包** - `ZipFiles(filename string, files []string) error` - 压缩多个文件到ZIP归档 - `ZipDir(sourceDir, targetZip string) error` - 将整个目录压缩到ZIP归档 - `UnzipFile(archive, target string) error` - 安全地解压ZIP到指定目录 **文件流操作** - `ReadLinesChan(filePath string) (<-chan string, <-chan error)` - 并发流式读取超大文本 **文件格式化** - `FileSizeFormat(size int64) string` - 格式化文件大小(B, KB, MB, GB等) #### 使用示例 ```go // 文件检查 if ixUtils.FileExists("test.txt") { fmt.Println("文件存在") } if ixUtils.IsDir("/tmp") { fmt.Println("是目录") } // 文件读写 content, err := ixUtils.ReadFile("config.txt") if err == nil { fmt.Println("文件内容:", content) } err = ixUtils.WriteFile("output.txt", "Hello, World!") if err != nil { log.Fatal(err) } // 文件操作 err = ixUtils.CopyFile("source.txt", "backup.txt") err = ixUtils.MoveFile("old.txt", "new.txt") // 目录操作 err = ixUtils.CreateDir("new_directory") files, err := ixUtils.ListFiles("./") fmt.Println("当前目录文件:", files) ``` ### ⏰ 时间工具 (time.go) 全面的时间处理工具,包含时间格式化、时间计算、时间比较、时区转换等功能。 #### 主要函数 **时间格式化** - `FormatTime(t time.Time, format string) string` - 格式化时间 - `ParseTime(timeStr, format string) (time.Time, error)` - 解析时间字符串 **时间获取** - `Now() time.Time` - 获取当前时间 - `Today() time.Time` - 获取今天的开始时间 - `Yesterday() time.Time` - 获取昨天的开始时间 - `Tomorrow() time.Time` - 获取明天的开始时间 **时间边界** - `StartOfDay(t time.Time) time.Time` - 获取指定时间的开始时间 - `EndOfDay(t time.Time) time.Time` - 获取指定时间的结束时间 - `StartOfWeek(t time.Time) time.Time` - 获取指定时间所在周的开始时间(周一) - `EndOfWeek(t time.Time) time.Time` - 获取指定时间所在周的结束时间(周日) - `StartOfMonth(t time.Time) time.Time` - 获取指定时间所在月的开始时间 - `EndOfMonth(t time.Time) time.Time` - 获取指定时间所在月的结束时间 - `StartOfYear(t time.Time) time.Time` - 获取指定时间所在年的开始时间 - `EndOfYear(t time.Time) time.Time` - 获取指定时间所在年的结束时间 **时间判断** - `IsToday(t time.Time) bool` - 判断时间是否为今天 - `IsSameDay(t1, t2 time.Time) bool` - 判断两个时间是否为同一天 - `IsWeekend(t time.Time) bool` - 判断时间是否为周末 - `IsWorkday(t time.Time) bool` - 判断时间是否为工作日 - `IsLeapYear(year int) bool` - 判断是否为闰年 **时间计算** - `AddDays(t time.Time, days int) time.Time` - 增加天数 - `AddMonths(t time.Time, months int) time.Time` - 增加月数 - `AddYears(t time.Time, years int) time.Time` - 增加年数 - `DiffDays(t1, t2 time.Time) int` - 计算两个时间相差的天数 - `DiffMonths(t1, t2 time.Time) int` - 计算两个时间相差的月数 - `DiffYears(t1, t2 time.Time) int` - 计算两个时间相差的年数 **时间戳转换** - `TimeToUnix(t time.Time) int64` - 时间转时间戳(秒) - `TimeToUnixMilli(t time.Time) int64` - 时间转时间戳(毫秒) - `UnixToTime(timestamp int64) time.Time` - 时间戳(秒)转时间 - `UnixMilliToTime(timestamp int64) time.Time` - 时间戳(毫秒)转时间 - `CurrentUnix() int64` - 获取当前时间戳(秒) - `CurrentUnixMilli() int64` - 获取当前时间戳(毫秒) - `CurrentUnixNano() int64` - 获取当前时间戳(纳秒) **时间格式化快捷方法** - `CurrentTime() string` - 获取当前时间字符串(2006-01-02 15:04:05) - `CurrentDate() string` - 获取当前日期字符串(2006-01-02) - `CurrentTimeShort() string` - 获取当前时间字符串(短格式) - `CurrentTimeLong() string` - 获取当前时间字符串(长格式) - `CurrentTimeRFC() string` - 获取当前时间字符串(RFC格式) **时间格式化** - `FormatDuration(d time.Duration) string` - 格式化时间间隔 **其他工具** - `GetAge(birthday time.Time) int` - 计算年龄 - `GetDaysInMonth(year int, month time.Month) int` - 获取指定年月的天数 - `GetWeekNumber(t time.Time) int` - 获取指定时间是一年中的第几周 - `GetQuarter(t time.Time) int` - 获取指定时间是一年中的第几季度 **时区处理** - `GetLocation(timezone string) (*time.Location, error)` - 获取指定时区 - `GetLocalLocation() *time.Location` - 获取本地时区 - `GetUTCLocation() *time.Location` - 获取UTC时区 - `GetChinaLocation() *time.Location` - 获取中国时区 - `ToLocation(t time.Time, timezone string) (time.Time, error)` - 将时间转换到指定时区 - `ToUTC(t time.Time) time.Time` - 将时间转换为UTC时间 - `ToLocal(t time.Time) time.Time` - 将时间转换为本地时间 - `ToChina(t time.Time) time.Time` - 将时间转换为中国时区 - `GetTimezoneOffset(timezone string) (int, error)` - 获取指定时区与UTC的偏移量 - `GetTimezoneName(timezone string) (string, error)` - 获取指定时区的名称 - `GetCurrentTimezone() string` - 获取当前时区 - `GetCurrentTimezoneOffset() int` - 获取当前时区与UTC的偏移量 - `IsValidTimezone(timezone string) bool` - 判断时区是否有效 #### 使用示例 ```go now := time.Now() // 时间格式化 formatted := ixUtils.FormatTime(now, ixUtils.TimeFormat) fmt.Println("格式化时间:", formatted) // 2006-01-02 15:04:05 // 时间计算 tomorrow := ixUtils.AddDays(now, 1) fmt.Println("明天:", ixUtils.FormatTime(tomorrow, ixUtils.TimeFormat)) // 时间差计算 days := ixUtils.DiffDays(tomorrow, now) fmt.Println("相差天数:", days) // 1 // 时间判断 fmt.Println("是否今天:", ixUtils.IsToday(now)) // true fmt.Println("是否周末:", ixUtils.IsWeekend(now)) // false fmt.Println("是否闰年:", ixUtils.IsLeapYear(2024)) // true // 获取特定时间 today := ixUtils.Today() weekStart := ixUtils.StartOfWeek(now) monthStart := ixUtils.StartOfMonth(now) fmt.Println("今天开始:", ixUtils.FormatTime(today, ixUtils.DateFormat)) fmt.Println("本周开始:", ixUtils.FormatTime(weekStart, ixUtils.DateFormat)) fmt.Println("本月开始:", ixUtils.FormatTime(monthStart, ixUtils.DateFormat)) // 时间戳转换 timestamp := ixUtils.CurrentUnix() fmt.Println("当前时间戳:", timestamp) // 时区转换 utcTime := ixUtils.ToUTC(now) chinaTime := ixUtils.ToChina(now) fmt.Println("UTC时间:", ixUtils.FormatTime(utcTime, ixUtils.TimeFormat)) fmt.Println("中国时间:", ixUtils.FormatTime(chinaTime, ixUtils.TimeFormat)) ``` ## 📦 安装 ### Go Modules ```bash go get gitee.com/ixgo/ixutils ``` ### 导入使用 ```go import "gitee.com/ixgo/ixutils" // 或者使用别名 import ixUtils "gitee.com/ixgo/ixutils" ``` ## 🚀 快速开始 ```go package main import ( "fmt" "gitee.com/ixgo/ixutils" ) func main() { // ID生成 uuid := ixUtils.GenerateUUID() fmt.Println("UUID:", uuid) // 字符串处理 camelCase := ixUtils.CamelCase("hello_world") fmt.Println("驼峰命名:", camelCase) // helloWorld // 数组操作 numbers := []int{1, 2, 3, 4, 5} doubled := ixUtils.Map(numbers, func(n int) int { return n * 2 }) fmt.Println("翻倍数组:", doubled) // [2, 4, 6, 8, 10] // 数学计算 average := ixUtils.Average(numbers) fmt.Println("平均值:", average) // 3.0 // 时间处理 now := ixUtils.Now() tomorrow := ixUtils.AddDays(now, 1) fmt.Println("明天:", ixUtils.FormatTime(tomorrow, ixUtils.TimeFormat)) // HTTP请求 resp, err := ixUtils.Get("https://api.github.com") if err == nil { body, _ := ixUtils.ReadResponseString(resp) fmt.Println("GitHub API响应:", body) } // 文件操作 if ixUtils.FileExists("config.json") { content, _ := ixUtils.ReadFileString("config.json") fmt.Println("配置内容:", content) } // 类型转换 num := ixUtils.MustInt("123") fmt.Println("转换结果:", num) // 123 // 三元运算 result := ixUtils.Ternary(10 > 5, "大于", "小于等于") fmt.Println(result) // "大于" } ``` ## 📊 功能统计 | 模块 | 函数数量 | 主要功能 | |------|----------|----------| | 🆔 ID生成 | 22+ | UUID、雪花ID、ObjectID、业务ID | | 🌐 网络工具 | 30+ | IP处理、网络检测、域名解析 | | 🔢 数学工具 | 25+ | 基础数学、统计计算、数值处理 | | 🔤 字符串工具 | 40+ | 格式化、验证、命名转换、脱敏、提取、统计 | | 📊 数组工具 | 30+ | 泛型数组操作、集合运算、分块、排序、分组 | | 🏗️ 结构体工具 | 20+ | 结构体转换、字段操作 | | 📄 JSON工具 | 15+ | JSON编解码、文件操作 | | 🔄 类型转换 | 20+ | 类型安全转换、默认值处理 | | 🌐 HTTP工具 | 15+ | HTTP请求、文件上传下载 | | 🔐 加密工具 | 15+ | MD5、SHA、HMAC、Base64 | | 🎲 随机工具 | 15+ | 随机数、字符串、数组操作 | | ⚙️ 配置管理 | 10+ | 多格式配置文件处理 | | 🔄 并发工具 | 15+ | 并发控制、工作池、信号量 | | 📁 文件工具 | 20+ | 文件操作、目录遍历 | | ⏰ 时间工具 | 25+ | 时间处理、格式化、计算 | | 🔢 版本比较 | 1+ | 语义化版本比较 | | 🔀 三元运算 | 4+ | 条件运算、空值处理 | | 🗺️ Map工具 | 20+ | Map操作、转换、分组 | | ❌ 错误处理 | 15+ | 错误包装、重试、合并 | | ✅ 验证工具 | 10+ | 身份证、银行卡、姓名验证 | **总计**: 350+ 个实用函数,涵盖19个功能模块 ## 🎯 使用场景 ### Web开发 - HTTP请求处理、JSON数据处理 - 用户输入验证、数据格式化 - 配置文件管理、日志处理 ### 数据处理 - 数据类型转换、结构体操作 - 数学计算、统计分析 ### 分布式系统 - 唯一ID生成(UUID、雪花ID) - 网络检测、服务健康检查 - 并发控制、任务调度 ### 文件管理 - 文件读写、目录操作 - 文件加密、完整性校验 - 批量文件处理 ### 工具开发 - 命令行工具、脚本开发 - 自动化任务、数据迁移 - 系统监控、性能分析 ### 🌱 环境变量工具 (env.go) 快捷、安全地读取系统环境变量,支持默认值和自动类型转换。 #### 主要函数 - `GetEnv(key, defaultVal string) string` - 获取字符串环境变量,空则返回默认值 - `GetEnvInt(key string, defaultVal int) int` - 获取并转换为整数 - `GetEnvBool(key string, defaultVal bool) bool` - 获取并转换为布尔值 - `GetEnvFloat(key string, defaultVal float64) float64` - 获取并转换为浮点数 #### 使用示例 ```go // 读取端口号,默认8080 port := ixUtils.GetEnvInt("PORT", 8080) // 读取调试模式,默认false debug := ixUtils.GetEnvBool("DEBUG", false) ``` ## 🤝 贡献 欢迎提交 Issue 和 Pull Request 来帮助改进这个工具包! ## 📄 许可证 MIT License ## 🔗 相关链接 - [源码仓库](https://gitee.com/ixgo/go-helper) - [API文档](https://pkg.go.dev/gitee.com/ixgo/ixutils) - [更新日志](CHANGELOG.md) --- **ixUtils** - 让Go开发更简单、更高效! 🚀