ixUtils

package
v0.0.0-...-0694354 Latest Latest
Warning

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

Go to latest
Published: Sep 19, 2025 License: Apache-2.0 Imports: 36 Imported by: 0

README

ixUtils - Go 语言工具包

Go Version License

ixUtils 是一个功能丰富的 Go 语言工具包,提供了日常开发中常用的工具函数,涵盖ID生成、Excel处理、网络工具、数学计算、字符串处理、数组操作、结构体操作、加密解密、HTTP 请求、并发控制、文件操作、时间处理等20多个功能模块。

✨ 特性

  • 🚀 高性能: 优化的算法实现,注重性能
  • 🔧 易用性: 简洁的 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格式
使用示例
import "gitee.com/ixgo/go-helper/utils"

// 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
📋 Excel处理工具 (excel.go)

全面的Excel和CSV处理工具,支持读写Excel文件、CSV文件,以及结构体与Excel的相互转换。

主要函数

基础Excel操作

  • ReadExcel(path string) ([][]string, error) - 读取Excel/CSV文件
  • ReadExcelSheet(path, sheetName string) ([][]string, error) - 读取指定工作表
  • WriteExcel(data [][]string, path string) error - 写入Excel/CSV文件
  • WriteExcelSheet(data [][]string, path, sheetName string) error - 写入指定工作表

结构体转换

  • ExcelToStruct(path string, result interface{}) error - Excel转结构体
  • ExcelToStructWithSheet(path, sheetName string, result interface{}) error - 指定工作表转结构体
  • StructToExcel(data interface{}, path string) error - 结构体转Excel
  • StructToExcelWithSheet(data interface{}, path, sheetName string) error - 结构体转指定工作表

工具函数

  • GetExcelSheets(path string) ([]string, error) - 获取所有工作表名称
  • GetExcelInfo(path string) (*ExcelInfo, error) - 获取Excel文件详细信息
  • ValidateExcelStruct(structType reflect.Type) error - 验证结构体是否适合Excel转换

CSV扩展

  • ReadCSVWithOptions(path string, options *CSVOptions) ([][]string, error) - 自定义选项读取CSV
  • WriteCSVWithOptions(data [][]string, path string, options *CSVOptions) error - 自定义选项写入CSV
  • DefaultCSVOptions() *CSVOptions - 获取默认CSV选项
使用示例
// 读取Excel文件
data, err := ixUtils.ReadExcel("data.xlsx")
if err != nil {
    log.Fatal(err)
}

// 结构体定义
type User struct {
    Name  string `excel:"姓名"`
    Age   int    `excel:"年龄"`
    Email string `excel:"邮箱"`
}

// Excel转结构体
var users []User
err = ixUtils.ExcelToStruct("users.xlsx", &users)

// 结构体转Excel
newUsers := []User{{Name: "张三", Age: 25, Email: "zhangsan@example.com"}}
err = ixUtils.StructToExcel(newUsers, "output.xlsx")
🌐 网络工具 (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 - 批量测试连接
使用示例
// 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 - 检查是否为奇数
使用示例
// 基础数学运算
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 - 重复字符串

字符串判断

  • IsBlank(str string) bool - 是否为空白字符串
  • IsNotEmpty(str string) bool - 是否非空
  • IsNotBlank(str 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 - 验证是否为字母数字
使用示例
// 字符串格式化
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 - 比较两个版本号大小
使用示例
// 版本号比较
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 - 数组差集
使用示例
// 基础操作
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
  • 等等...
使用示例
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)
📄 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解码
  • 等等...
使用示例
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)

强大的类型转换工具,支持字符串、数字、布尔值等类型之间的相互转换。

主要函数

字符串转换

  • StringToInt(str string) (int, error) - 字符串转整数
  • StringToInt64(str string) (int64, error) - 字符串转64位整数
  • StringToFloat(str string) (float64, error) - 字符串转浮点数
  • StringToBool(str string) (bool, error) - 字符串转布尔值

数字转换

  • IntToString(num int) string - 整数转字符串
  • Int64ToString(num int64) string - 64位整数转字符串
  • FloatToString(num float64) string - 浮点数转字符串
  • BoolToString(b bool) string - 布尔值转字符串

安全转换 (带默认值)

  • StringToIntWithDefault(str string, defaultValue int) int - 字符串转整数(带默认值)
  • StringToInt64WithDefault(str string, defaultValue int64) int64 - 字符串转64位整数(带默认值)
  • StringToFloatWithDefault(str string, defaultValue float64) float64 - 字符串转浮点数(带默认值)
  • StringToBoolWithDefault(str string, defaultValue bool) bool - 字符串转布尔值(带默认值)

接口转换

  • InterfaceToString(v interface{}) string - 接口转字符串
  • InterfaceToInt(v interface{}) (int, error) - 接口转整数
  • InterfaceToFloat(v interface{}) (float64, error) - 接口转浮点数
  • InterfaceToBool(v interface{}) (bool, error) - 接口转布尔值
使用示例
// 字符串转换
num, err := ixUtils.StringToInt("123")
fmt.Println("字符串转整数:", num) // 123

// 安全转换 (带默认值)
num2 := ixUtils.StringToIntWithDefault("abc", 0)
fmt.Println("安全转换:", num2) // 0 (转换失败使用默认值)

// 数字转换
str := ixUtils.IntToString(456)
fmt.Println("整数转字符串:", str) // "456"

// 接口转换
var value interface{} = "789"
num3, err := ixUtils.InterfaceToInt(value)
fmt.Println("接口转整数:", num3) // 789
🔀 三元运算 (ternary.go)

提供三元运算符和空值合并等便捷函数。

主要函数
  • Ternary[T any](cond bool, a, b T) T - 三元运算符
  • Coalesce[T comparable](values ...T) T - 返回第一个非零值
  • IfThenElse[T any](cond bool, ifFunc, elseFunc func() T) T - 条件执行函数
  • Switch[T comparable, R any](value T, cases map[T]R, defaultValue R) R - Switch语句
使用示例
// 三元运算符
result := ixUtils.Ternary(10 > 5, "大于", "小于等于")
fmt.Println(result) // "大于"

// 空值合并
str := ixUtils.Coalesce("", "默认值", "其他")
fmt.Println(str) // "默认值"

// 条件执行
result2 := ixUtils.IfThenElse(true, 
    func() string { return "执行if" },
    func() string { return "执行else" })
fmt.Println(result2) // "执行if"
🌐 HTTP工具 (http.go)

全面的HTTP请求工具,支持GET、POST、PUT、DELETE等各种HTTP方法,以及文件上传、Cookie管理等功能。

主要函数

基础HTTP请求

  • HttpGet(url string, config ...*HttpConfig) (*HttpResponse, error) - GET请求
  • HttpPost(url string, data interface{}, config ...*HttpConfig) (*HttpResponse, error) - POST请求
  • HttpPut(url string, data interface{}, config ...*HttpConfig) (*HttpResponse, error) - PUT请求
  • HttpDelete(url string, config ...*HttpConfig) (*HttpResponse, error) - DELETE请求

表单和文件上传

  • HttpPostForm(url string, data map[string]string, config ...*HttpConfig) (*HttpResponse, error) - 表单提交
  • HttpUploadFile(url, fieldName, filePath string, config ...*HttpConfig) (*HttpResponse, error) - 文件上传
  • HttpUploadMultipleFiles(url string, files map[string]string, config ...*HttpConfig) (*HttpResponse, error) - 多文件上传

下载功能

  • HttpDownloadFile(url, filePath string, config ...*HttpConfig) error - 文件下载
  • HttpDownloadWithProgress(url, filePath string, progress func(downloaded, total int64), config ...*HttpConfig) error - 带进度的下载

客户端管理

  • NewHttpClient(config *HttpConfig) *http.Client - 创建HTTP客户端
  • SetDefaultHttpConfig(config *HttpConfig) - 设置默认配置
使用示例
// 基础GET请求
resp, err := ixUtils.HttpGet("https://api.example.com/users")
if err == nil {
    fmt.Println("响应状态:", resp.StatusCode)
    fmt.Println("响应内容:", resp.Text)
}

// POST请求发送JSON
data := map[string]interface{}{
    "name": "张三",
    "age":  25,
}
resp, err = ixUtils.HttpPost("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.HttpGet("https://api.example.com/protected", config)

// 文件上传
err = ixUtils.HttpUploadFile("https://api.example.com/upload", "file", "/path/to/file.jpg")

// 文件下载
err = ixUtils.HttpDownloadFile("https://example.com/file.zip", "/path/to/save/file.zip")
🔐 加密工具 (crypto.go)

全面的加密和编码工具,支持MD5、SHA系列、HMAC、Base64、Hex等多种加密和编码方式。

主要函数

MD5加密

  • MD5(str string) string - 计算字符串的MD5值
  • MD5File(filePath string) (string, error) - 计算文件的MD5值

SHA系列加密

  • SHA1(str string) string - 计算字符串的SHA1值
  • SHA256(str string) string - 计算字符串的SHA256值
  • SHA512(str string) string - 计算字符串的SHA512值
  • SHA1File(filePath string) (string, error) - 计算文件的SHA1值
  • SHA256File(filePath string) (string, error) - 计算文件的SHA256值
  • SHA512File(filePath string) (string, error) - 计算文件的SHA512值

HMAC加密

  • HmacSHA1(str, key string) string - HMAC-SHA1加密
  • HmacSHA256(str, key string) string - HMAC-SHA256加密
  • HmacSHA512(str, key string) string - HMAC-SHA512加密

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解码
使用示例
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(length int) string - 生成指定长度的随机字符串
  • RandomStringWithCharset(length int, charset string) string - 使用指定字符集生成随机字符串
  • RandomNumberString(length int) string - 生成指定长度的随机数字字符串
  • RandomLetterString(length int) string - 生成指定长度的随机字母字符串

随机选择

  • RandomChoice[T any](slice []T) T - 从切片中随机选择一个元素
  • RandomChoices[T any](slice []T, count int) []T - 从切片中随机选择多个元素
  • RandomSample[T any](slice []T, count int) []T - 从切片中随机采样(不重复)

随机布尔和概率

  • RandomBool() bool - 生成随机布尔值
  • RandomBoolWithProbability(probability float64) bool - 按概率生成布尔值

数组打乱

  • Shuffle[T any](slice []T) []T - 打乱数组顺序
  • ShuffleInPlace[T any](slice []T) - 原地打乱数组
使用示例
// 随机数生成
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)
⚙️ 配置管理 (config.go)

强大的配置文件处理工具,支持JSON、YAML、ENV等多种格式的配置文件。

主要函数

配置加载

  • LoadConfig(filePath string) (Config, error) - 加载配置文件
  • LoadJsonConfig(filePath string) (Config, error) - 加载JSON配置
  • LoadYamlConfig(filePath string) (Config, error) - 加载YAML配置
  • LoadEnvConfig() Config - 加载环境变量配置

配置操作

  • Get(key string) interface{} - 获取配置值
  • GetString(key string) string - 获取字符串配置
  • GetInt(key string) int - 获取整数配置
  • GetBool(key string) bool - 获取布尔配置
  • GetStringSlice(key string) []string - 获取字符串数组配置

配置保存

  • SaveConfig(config Config, filePath string) error - 保存配置到文件
  • SaveJsonConfig(config Config, filePath string) error - 保存为JSON格式
  • SaveYamlConfig(config Config, filePath string) error - 保存为YAML格式
使用示例
// 加载配置文件
config, err := ixUtils.LoadConfig("config.json")
if err != nil {
    log.Fatal(err)
}

// 获取配置值
dbHost := config.GetString("database.host")
dbPort := config.GetInt("database.port")
debug := config.GetBool("debug")

fmt.Printf("数据库: %s:%d, 调试模式: %v\n", dbHost, dbPort, debug)

// 环境变量配置
envConfig := ixUtils.LoadEnvConfig()
port := envConfig.GetString("PORT")
🔄 并发工具 (concurrent.go)

强大的并发控制工具,提供增强版的WaitGroup、工作池、并发限制等功能。

主要函数

增强WaitGroup

  • NewWaitGroup(ctx context.Context, timeout time.Duration) *WaitGroup - 创建支持超时和取消的WaitGroup
  • Add(delta int) - 添加等待计数
  • Done() - 完成一个任务
  • Wait() error - 等待所有任务完成

工作池

  • NewWorkerPool(size int) *WorkerPool - 创建工作池
  • Submit(task func()) - 提交任务
  • SubmitWithResult[T any](task func() T) <-chan T - 提交有返回值的任务
  • Close() - 关闭工作池

并发限制

  • NewSemaphore(capacity int) *Semaphore - 创建信号量
  • Acquire() error - 获取资源
  • Release() - 释放资源
  • TryAcquire() bool - 尝试获取资源

并发安全计数器

  • NewCounter() *Counter - 创建计数器
  • Increment() int64 - 递增
  • Decrement() int64 - 递减
  • Get() int64 - 获取当前值
使用示例
// 使用增强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.NewWorkerPool(3)
defer pool.Close()

for i := 0; i < 10; i++ {
    taskID := i
    pool.Submit(func() {
        fmt.Printf("执行任务 %d\n", taskID)
        time.Sleep(time.Second)
    })
}

// 使用信号量限制并发
sem := ixUtils.NewSemaphore(2) // 最多2个并发

for i := 0; i < 5; i++ {
    go func(id int) {
        sem.Acquire() // 获取资源
        defer sem.Release() // 释放资源
        
        fmt.Printf("任务 %d 开始执行\n", id)
        time.Sleep(2 * time.Second)
        fmt.Printf("任务 %d 执行完成\n", id)
    }(i)
}
📁 文件工具 (file.go)

全面的文件操作工具,支持文件读写、目录操作、文件信息获取等功能。

主要函数

文件检查

  • FileExists(path string) bool - 检查文件是否存在
  • IsDir(path string) bool - 检查路径是否为目录
  • IsFile(path string) bool - 检查路径是否为文件
  • GetFileSize(path string) (int64, error) - 获取文件大小

文件读写

  • ReadFile(path string) (string, error) - 读取文件内容
  • ReadFileBytes(path string) ([]byte, error) - 读取文件字节
  • WriteFile(path, content string) error - 写入文件内容
  • WriteFileBytes(path string, data []byte) error - 写入文件字节
  • AppendFile(path, 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 - 删除目录

文件信息

  • GetFileInfo(path string) (os.FileInfo, error) - 获取文件信息
  • GetFileExt(path string) string - 获取文件扩展名
  • GetFileName(path string) string - 获取文件名
  • GetFileDir(path string) string - 获取文件目录

目录遍历

  • ListFiles(dir string) ([]string, error) - 列出目录中的文件
  • ListDirs(dir string) ([]string, error) - 列出目录中的子目录
  • WalkDir(root string, walkFn filepath.WalkFunc) error - 遍历目录
使用示例
// 文件检查
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) - 解析时间字符串
  • TimeToString(t time.Time) string - 时间转字符串
  • StringToTime(timeStr string) (time.Time, error) - 字符串转时间

时间计算

  • AddDays(t time.Time, days int) time.Time - 添加天数
  • AddHours(t time.Time, hours int) time.Time - 添加小时
  • AddMinutes(t time.Time, minutes int) time.Time - 添加分钟
  • DiffDays(t1, t2 time.Time) int - 计算天数差
  • DiffHours(t1, t2 time.Time) int - 计算小时差
  • DiffMinutes(t1, t2 time.Time) int - 计算分钟差

时间判断

  • IsToday(t time.Time) bool - 是否为今天
  • IsYesterday(t time.Time) bool - 是否为昨天
  • IsTomorrow(t time.Time) bool - 是否为明天
  • IsWeekend(t time.Time) bool - 是否为周末
  • IsLeapYear(year int) bool - 是否为闰年

时间获取

  • GetNow() time.Time - 获取当前时间
  • GetToday() time.Time - 获取今天开始时间
  • GetYesterday() time.Time - 获取昨天开始时间
  • GetTomorrow() time.Time - 获取明天开始时间
  • GetWeekStart(t time.Time) time.Time - 获取周开始时间
  • GetMonthStart(t time.Time) time.Time - 获取月开始时间

时区转换

  • ConvertTimeZone(t time.Time, fromZone, toZone string) (time.Time, error) - 时区转换
  • ToUTC(t time.Time) time.Time - 转换为UTC时间
  • ToLocal(t time.Time) time.Time - 转换为本地时间
使用示例
now := time.Now()

// 时间格式化
formatted := ixUtils.FormatTime(now, ixUtils.TimeFormat)
fmt.Println("格式化时间:", formatted)

// 时间计算
tomorrow := ixUtils.AddDays(now, 1)
fmt.Println("明天:", ixUtils.TimeToString(tomorrow))

// 时间差计算
days := ixUtils.DiffDays(tomorrow, now)
fmt.Println("相差天数:", days)

// 时间判断
fmt.Println("是否今天:", ixUtils.IsToday(now))
fmt.Println("是否周末:", ixUtils.IsWeekend(now))
fmt.Println("是否闰年:", ixUtils.IsLeapYear(2024))

// 获取特定时间
today := ixUtils.GetToday()
weekStart := ixUtils.GetWeekStart(now)
monthStart := ixUtils.GetMonthStart(now)

fmt.Println("今天开始:", ixUtils.TimeToString(today))
fmt.Println("本周开始:", ixUtils.TimeToString(weekStart))
fmt.Println("本月开始:", ixUtils.TimeToString(monthStart))

// 时区转换
utcTime := ixUtils.ToUTC(now)
fmt.Println("UTC时间:", ixUtils.TimeToString(utcTime))

📦 安装

Go Modules
go get gitee.com/ixgo/go-helper/utils
导入使用
import "gitee.com/ixgo/go-helper/utils"

// 或者使用别名
import ixUtils "gitee.com/ixgo/go-helper/utils"

🚀 快速开始

package main

import (
    "fmt"
    "gitee.com/ixgo/go-helper/utils"
)

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.GetNow()
    tomorrow := ixUtils.AddDays(now, 1)
    fmt.Println("明天:", ixUtils.TimeToString(tomorrow))
    
    // HTTP请求
    resp, err := ixUtils.HttpGet("https://api.github.com")
    if err == nil {
        fmt.Println("GitHub API状态:", resp.StatusCode)
    }
    
    // 文件操作
    if ixUtils.FileExists("config.json") {
        content, _ := ixUtils.ReadFile("config.json")
        fmt.Println("配置内容:", content)
    }
}

📊 功能统计

模块 函数数量 主要功能
🆔 ID生成 22+ UUID、雪花ID、ObjectID、业务ID
📋 Excel处理 14+ Excel/CSV读写、结构体转换
🌐 网络工具 30+ IP处理、网络检测、域名解析
🔢 数学工具 25+ 基础数学、统计计算、数值处理
🔤 字符串工具 19+ 格式化、验证、命名转换
📊 数组工具 13+ 泛型数组操作、集合运算
🏗️ 结构体工具 20+ 结构体转换、字段操作
📄 JSON工具 15+ JSON编解码、文件操作
🔄 类型转换 20+ 类型安全转换、默认值处理
🌐 HTTP工具 15+ HTTP请求、文件上传下载
🔐 加密工具 15+ MD5、SHA、HMAC、Base64
🎲 随机工具 15+ 随机数、字符串、数组操作
⚙️ 配置管理 10+ 多格式配置文件处理
🔄 并发工具 15+ 并发控制、工作池、信号量
📁 文件工具 20+ 文件操作、目录遍历
⏰ 时间工具 25+ 时间处理、格式化、计算
🔢 版本比较 1+ 语义化版本比较
🔀 三元运算 4+ 条件运算、空值处理

总计: 300+ 个实用函数,涵盖18个功能模块

🎯 使用场景

Web开发
  • HTTP请求处理、JSON数据处理
  • 用户输入验证、数据格式化
  • 配置文件管理、日志处理
数据处理
  • Excel/CSV文件处理
  • 数据类型转换、结构体操作
  • 数学计算、统计分析
分布式系统
  • 唯一ID生成(UUID、雪花ID)
  • 网络检测、服务健康检查
  • 并发控制、任务调度
文件管理
  • 文件读写、目录操作
  • 文件加密、完整性校验
  • 批量文件处理
工具开发
  • 命令行工具、脚本开发
  • 自动化任务、数据迁移
  • 系统监控、性能分析

🤝 贡献

欢迎提交 Issue 和 Pull Request 来帮助改进这个工具包!

📄 许可证

MIT License

🔗 相关链接


ixUtils - 让Go开发更简单、更高效! 🚀

Documentation

Overview

* @Author: lixu lixu@puchigames.com * @Date: 2025-07-03 16:49:48 * @LastEditors: lixu lixu@puchigames.com * @LastEditTime: 2025-07-03 16:52:02 * @FilePath: /go-helper/utils/array.go * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE

* @Author: lixu lixu@puchigames.com * @Date: 2025-06-16 11:00:00 * @LastEditors: lixu lixu@puchigames.com * @LastEditTime: 2025-06-16 10:53:12 * @FilePath: /go-helper/utils/config.go * @Description: 配置文件处理工具函数,支持JSON、YAML、ENV等格式的配置文件

* @Author: lixu lixu@puchigames.com * @Date: 2025-06-16 10:17:13 * @LastEditors: lixu lixu@puchigames.com * @LastEditTime: 2025-06-16 10:17:20 * @FilePath: /go-helper/utils/convert.go * @Description: 类型转换工具函数,包含字符串、数字、布尔值等类型之间的相互转换功能

* @Author: lixu lixu@puchigames.com * @Date: 2025-06-16 10:37:05 * @LastEditors: lixu lixu@puchigames.com * @LastEditTime: 2025-06-16 10:39:33 * @FilePath: /go-helper/utils/crypto.go * @Description: 加密相关工具函数,包含MD5、SHA系列、HMAC、Base64、Hex等加密和编码功能

* @Author: lixu lixu@puchigames.com * @Date: 2025-06-16 10:17:13 * @LastEditors: lixu lixu@puchigames.com * @LastEditTime: 2025-06-16 16:17:54 * @FilePath: /go-helper/utils/file.go * @Description: 文件操作工具函数,包含文件读写、目录操作、文件信息获取等功能

* @Author: lixu lixu@puchigames.com * @Date: 2025-06-16 10:40:44 * @LastEditors: lixu lixu@puchigames.com * @LastEditTime: 2025-06-17 10:44:20 * @FilePath: /go-helper/utils/http.go * @Description: HTTP相关工具函数,包含请求、响应、Cookie、Session等处理功能

* @Author: lixu lixu@puchigames.com * @Date: 2025-06-16 10:17:13 * @LastEditors: lixu lixu@puchigames.com * @LastEditTime: 2025-06-16 10:17:20 * @FilePath: /go-helper/utils/random.go * @Description: 随机数生成工具函数,包含随机整数、随机字符串、随机数组、随机UUID等功能

* @Author: lixu lixu@puchigames.com * @Date: 2025-06-16 10:17:13 * @LastEditors: lixu lixu@puchigames.com * @LastEditTime: 2025-06-16 10:17:20 * @FilePath: /go-helper/utils/struct.go * @Description: 结构体处理工具函数,包含结构体转换、字段操作、标签处理等功能

* @Author: lixu lixu@puchigames.com * @Date: 2025-07-03 16:43:02 * @LastEditors: lixu lixu@puchigames.com * @LastEditTime: 2025-07-03 16:48:52 * @FilePath: /go-helper/utils/ternary.go * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE

* @Author: lixu lixu@puchigames.com * @Date: 2025-06-16 10:28:18 * @LastEditors: lixu lixu@puchigames.com * @LastEditTime: 2025-06-16 10:40:09 * @FilePath: /go-helper/utils/time.go * @Description: 时间处理工具函数,包含时间格式化、时间计算、时间比较、时区转换等功能

Index

Constants

View Source
const (
	// 时间格式化模板
	TimeFormat      = "2006-01-02 15:04:05"
	DateFormat      = "2006-01-02"
	TimeFormatShort = "2006-01-02 15:04"
	TimeFormatLong  = "2006-01-02 15:04:05.000"
	TimeFormatRFC   = time.RFC3339
)

Variables

View Source
var DefaultHttpConfig = HttpConfig{
	Timeout:    30 * time.Second,
	RetryTimes: 3,
	RetryDelay: time.Second,
	Headers: map[string]string{
		"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
	},
	MaxRedirect: 5,
}

DefaultHttpConfig 默认HTTP配置

View Source
var DefaultValue = struct {
	Int    int
	Int64  int64
	Float  float64
	Bool   bool
	String string
}{
	Int:    0,
	Int64:  0,
	Float:  0.0,
	Bool:   false,
	String: "",
}

DefaultValue 定义默认值

View Source
var ErrCancelled = errors.New("operation cancelled")

ErrCancelled 取消错误

View Source
var ErrTimeout = errors.New("operation timed out")

ErrTimeout 超时错误

Functions

func Abs

func Abs[T int | int64 | float64](n T) T

Abs 泛型版本的绝对值函数

func AbsFloat64

func AbsFloat64(f float64) float64

AbsFloat64 返回浮点数的绝对值

func AbsInt

func AbsInt(n int) int

AbsInt 返回整数的绝对值

func AbsInt64

func AbsInt64(n int64) int64

AbsInt64 返回64位整数的绝对值

func AddDays

func AddDays(t time.Time, days int) time.Time

AddDays 增加天数

func AddMonths

func AddMonths(t time.Time, months int) time.Time

AddMonths 增加月数

func AddYears

func AddYears(t time.Time, years int) time.Time

AddYears 增加年数

func All

func All[T any](arr []T, f func(T) bool) bool

All 判断是否所有元素都满足条件

func Any

func Any[T any](arr []T, f func(T) bool) bool

Any 判断是否有元素满足条件

func AppendFile

func AppendFile(path string, data []byte) error

AppendFile 追加内容到文件

func AppendFileString

func AppendFileString(path string, content string) error

AppendFileString 追加字符串到文件

func Average

func Average[T int | int64 | float64](numbers []T) float64

Average 泛型版本的平均值计算

func AverageFloat64

func AverageFloat64(numbers []float64) float64

AverageFloat64 计算浮点数数组的平均值

func AverageInt

func AverageInt(numbers []int) float64

AverageInt 计算整数数组的平均值

func Base64Decode

func Base64Decode(str string) (string, error)

Base64Decode Base64解码

func Base64Encode

func Base64Encode(str string) string

Base64Encode Base64编码

func Base64URLDecode

func Base64URLDecode(str string) (string, error)

Base64URLDecode URL安全的Base64解码

func Base64URLEncode

func Base64URLEncode(str string) string

Base64URLEncode URL安全的Base64编码

func BuildUrl

func BuildUrl(baseUrl string, params map[string]string) string

BuildUrl 构建URL

func CamelCase

func CamelCase(str string) string

CamelCase 转换为驼峰命名(首字母小写)

func Capitalize

func Capitalize(str string) string

Capitalize 将字符串首字母大写

func Ceil

func Ceil(f float64) int

Ceil 向上取整

func Clamp

func Clamp[T int | int64 | float64](value, min, max T) T

Clamp 泛型版本的数值限制

func ClampFloat64

func ClampFloat64(value, min, max float64) float64

ClampFloat64 将浮点数限制在指定范围内

func ClampInt

func ClampInt(value, min, max int) int

ClampInt 将整数限制在指定范围内

func Coalesce

func Coalesce[T comparable](values ...T) T

Coalesce 返回第一个非零值,否则返回默认值 s := Coalesce("", "默认值", "其他") // 返回 "默认值"

func CompareVersion

func CompareVersion(v1, v2 string) int

CompareVersion 比较版本号大小 返回值:1表示v1>v2,-1表示v1<v2,0表示v1=v2 支持格式:1.2.3、v1.2.3、1.2.3-alpha、1.2.3.4等

func Concat

func Concat[T any](slices ...[]T) []T

Concat 合并多个切片,返回新切片

func Contains

func Contains[T comparable](arr []T, v T) bool

Contains 判断切片是否包含某元素

func CopyFile

func CopyFile(src, dst string) error

CopyFile 复制文件

func CopyStruct

func CopyStruct(src, dst interface{}) error

CopyStruct 复制结构体(浅拷贝)

func CreateDir

func CreateDir(path string) error

CreateDir 创建目录

func CurrentDate

func CurrentDate() string

CurrentDate 获取当前日期字符串,格式:2006-01-02

func CurrentTime

func CurrentTime() string

CurrentTime 获取当前时间字符串,格式:2006-01-02 15:04:05

func CurrentTimeLong

func CurrentTimeLong() string

CurrentTimeLong 获取当前时间字符串(长格式),格式:2006-01-02 15:04:05.000

func CurrentTimeRFC

func CurrentTimeRFC() string

CurrentTimeRFC 获取当前时间字符串(RFC格式)

func CurrentTimeShort

func CurrentTimeShort() string

CurrentTimeShort 获取当前时间字符串(短格式),格式:2006-01-02 15:04

func CurrentUnix

func CurrentUnix() int64

CurrentUnix 获取当前时间戳(秒)

func CurrentUnixMilli

func CurrentUnixMilli() int64

CurrentUnixMilli 获取当前时间戳(毫秒)

func CurrentUnixNano

func CurrentUnixNano() int64

CurrentUnixNano 获取当前时间戳(纳秒)

func Default

func Default[T comparable](v, def T) T

Default 如果 v 为零值则返回 def,否则返回 v

func Delete

func Delete(url string, config ...*HttpConfig) (*http.Response, error)

Delete 发送DELETE请求

func DeleteDir

func DeleteDir(path string) error

DeleteDir 删除目录

func DeleteFile

func DeleteFile(path string) error

DeleteFile 删除文件

func DiffDays

func DiffDays(t1, t2 time.Time) int

DiffDays 计算两个时间相差的天数

func DiffMonths

func DiffMonths(t1, t2 time.Time) int

DiffMonths 计算两个时间相差的月数

func DiffYears

func DiffYears(t1, t2 time.Time) int

DiffYears 计算两个时间相差的年数

func Difference

func Difference[T comparable](a, b []T) []T

Difference 求 a 相对于 b 的差集(a 中有而 b 中没有的元素)

func EndOfDay

func EndOfDay(t time.Time) time.Time

EndOfDay 获取指定时间的结束时间

func EndOfMonth

func EndOfMonth(t time.Time) time.Time

EndOfMonth 获取指定时间所在月的结束时间

func EndOfWeek

func EndOfWeek(t time.Time) time.Time

EndOfWeek 获取指定时间所在周的结束时间(周日)

func EndOfYear

func EndOfYear(t time.Time) time.Time

EndOfYear 获取指定时间所在年的结束时间

func ExcelToStruct

func ExcelToStruct(path string, result interface{}) error

ExcelToStruct Excel转结构体切片

func ExcelToStructWithSheet

func ExcelToStructWithSheet(path string, sheetName string, result interface{}) error

ExcelToStructWithSheet Excel转结构体切片(指定工作表)

func FileExists

func FileExists(path string) bool

FileExists 检查文件是否存在

func FileModTime

func FileModTime(path string) (time.Time, error)

FileModTime 获取文件修改时间

func FileMode

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

FileMode 获取文件权限模式

func FileSize

func FileSize(path string) (int64, error)

FileSize 获取文件大小

func FileSizeFormat

func FileSizeFormat(size int64) string

FileSizeFormat 格式化文件大小

func Filter

func Filter[T any](arr []T, f func(T) bool) []T

Filter 过滤,返回满足条件的新切片

func Floor

func Floor(f float64) int

Floor 向下取整

func FormatDuration

func FormatDuration(d time.Duration) string

FormatDuration 格式化时间间隔

func FormatTime

func FormatTime(t time.Time, format string) string

FormatTime 格式化时间为字符串

func GCD

func GCD(a, b int) int

GCD 计算最大公约数

func GenerateAPIKey

func GenerateAPIKey() string

GenerateAPIKey 生成API密钥

func GenerateNanoID

func GenerateNanoID(size int) string

GenerateNanoID 生成NanoID风格的ID

func GenerateObjectID

func GenerateObjectID() string

GenerateObjectID 生成ObjectID (MongoDB风格)

func GenerateOrderID

func GenerateOrderID() string

GenerateOrderID 生成订单ID (时间戳+随机数)

func GenerateRequestID

func GenerateRequestID() string

GenerateRequestID 生成请求ID

func GenerateSecretKey

func GenerateSecretKey() string

GenerateSecretKey 生成密钥

func GenerateSessionID

func GenerateSessionID() string

GenerateSessionID 生成会话ID

func GenerateShortID

func GenerateShortID() string

GenerateShortID 生成短ID (8-12字符)

func GenerateShortIDWithLength

func GenerateShortIDWithLength(length int) string

GenerateShortIDWithLength 生成指定长度的短ID

func GenerateShortUUID

func GenerateShortUUID() string

GenerateShortUUID 生成短UUID (22字符)

func GenerateSimpleUUID

func GenerateSimpleUUID() string

GenerateSimpleUUID 生成简单UUID (无连字符)

func GenerateSnowflakeID

func GenerateSnowflakeID() int64

GenerateSnowflakeID 生成雪花ID (使用全局生成器)

func GenerateSpanID

func GenerateSpanID() string

GenerateSpanID 生成Span ID

func GenerateTraceID

func GenerateTraceID() string

GenerateTraceID 生成链路追踪ID

func GenerateUUID

func GenerateUUID() string

GenerateUUID 生成标准UUID (RFC 4122 Version 4)

func GenerateUUIDv1

func GenerateUUIDv1() string

GenerateUUIDv1 生成UUID Version 1 (基于时间和MAC地址)

func GenerateUUIDv4

func GenerateUUIDv4() string

GenerateUUIDv4 生成UUID Version 4 (随机)

func Get

func Get(url string, config ...*HttpConfig) (*http.Response, error)

Get 发送GET请求

func GetAge

func GetAge(birthday time.Time) int

GetAge 计算年龄

func GetAllMACAddresses

func GetAllMACAddresses() map[string]string

GetAllMACAddresses 获取所有网络接口的MAC地址

func GetChinaLocation

func GetChinaLocation() *time.Location

GetChinaLocation 获取中国时区

func GetCookie

func GetCookie(resp *http.Response, name string) *http.Cookie

GetCookie 获取指定名称的Cookie

func GetCookies

func GetCookies(resp *http.Response) []*http.Cookie

GetCookies 获取响应中的Cookie

func GetCurrentTimezone

func GetCurrentTimezone() string

GetCurrentTimezone 获取当前时区

func GetCurrentTimezoneAbbr

func GetCurrentTimezoneAbbr() string

GetCurrentTimezoneAbbr 获取当前时区的缩写

func GetCurrentTimezoneOffset

func GetCurrentTimezoneOffset() int

GetCurrentTimezoneOffset 获取当前时区与UTC的偏移量(秒)

func GetDaysInMonth

func GetDaysInMonth(year int, month time.Month) int

GetDaysInMonth 获取指定年月的天数

func GetDomainIP

func GetDomainIP(domain string) []string

GetDomainIP 获取域名对应的IP地址列表

func GetDomainIPWithTimeout

func GetDomainIPWithTimeout(domain string, timeout time.Duration) []string

GetDomainIPWithTimeout 带超时的域名解析

func GetDomainIPv4

func GetDomainIPv4(domain string) []string

GetDomainIPv4 获取域名对应的IPv4地址列表

func GetDomainIPv6

func GetDomainIPv6(domain string) []string

GetDomainIPv6 获取域名对应的IPv6地址列表

func GetExcelSheets

func GetExcelSheets(path string) ([]string, error)

GetExcelSheets 获取Excel文件的所有工作表名称

func GetFileExt

func GetFileExt(path string) string

GetFileExt 获取文件扩展名

func GetFileName

func GetFileName(path string) string

GetFileName 获取文件名(不含扩展名)

func GetFilePath

func GetFilePath(path string) string

GetFilePath 获取文件所在目录

func GetFreePort

func GetFreePort() (int, error)

GetFreePort 获取一个可用的端口号

func GetLocalIP

func GetLocalIP() string

GetLocalIP 获取本机内网IP地址

func GetLocalIPs

func GetLocalIPs() []string

GetLocalIPs 获取本机所有内网IP地址

func GetLocalLocation

func GetLocalLocation() *time.Location

GetLocalLocation 获取本地时区

func GetLocation

func GetLocation(timezone string) (*time.Location, error)

GetLocation 获取指定时区

func GetMACAddress

func GetMACAddress() string

GetMACAddress 获取本机MAC地址

func GetPublicIP

func GetPublicIP() string

GetPublicIP 获取公网IP地址

func GetQuarter

func GetQuarter(t time.Time) int

GetQuarter 获取指定时间是一年中的第几季度

func GetStructFieldType

func GetStructFieldType(obj interface{}, fieldName string) (reflect.Type, error)

GetStructFieldType 获取结构体指定字段的类型

func GetStructFieldValue

func GetStructFieldValue(obj interface{}, fieldName string) (interface{}, error)

GetStructFieldValue 获取结构体指定字段的值

func GetStructFields

func GetStructFields(obj interface{}) []string

GetStructFields 获取结构体的所有字段名

func GetStructTags

func GetStructTags(obj interface{}, tagName string) map[string]string

GetStructTags 获取结构体指定tag的所有字段值

func GetTimezoneAbbr

func GetTimezoneAbbr(timezone string) (string, error)

GetTimezoneAbbr 获取指定时区的缩写

func GetTimezoneList

func GetTimezoneList() []string

GetTimezoneList 获取所有可用的时区列表

func GetTimezoneName

func GetTimezoneName(timezone string) (string, error)

GetTimezoneName 获取指定时区的名称

func GetTimezoneOffset

func GetTimezoneOffset(timezone string) (int, error)

GetTimezoneOffset 获取指定时区与UTC的偏移量(秒)

func GetUTCLocation

func GetUTCLocation() *time.Location

GetUTCLocation 获取UTC时区

func GetWeekNumber

func GetWeekNumber(t time.Time) int

GetWeekNumber 获取指定时间是一年中的第几周

func HMACMD5

func HMACMD5(key, str string) string

HMACMD5 计算字符串的HMAC-MD5值

func HMACSHA1

func HMACSHA1(key, str string) string

HMACSHA1 计算字符串的HMAC-SHA1值

func HMACSHA256

func HMACSHA256(key, str string) string

HMACSHA256 计算字符串的HMAC-SHA256值

func HMACSHA512

func HMACSHA512(key, str string) string

HMACSHA512 计算字符串的HMAC-SHA512值

func HasStructField

func HasStructField(obj interface{}, fieldName string) bool

HasStructField 检查结构体是否包含指定字段

func HexDecode

func HexDecode(str string) (string, error)

HexDecode 十六进制解码

func HexEncode

func HexEncode(str string) string

HexEncode 十六进制编码

func HttpRequest

func HttpRequest(method, url string, body interface{}, config *HttpConfig) (*http.Response, error)

HttpRequest HTTP请求

func IPToInt

func IPToInt(ip string) uint32

IPToInt 将IP地址转换为32位无符号整数

func IfErr

func IfErr[T any](err error, a, b T) T

IfErr error 不为 nil 返回 b,否则返回 a result := IfErr(err, data, defaultData)

func InRange

func InRange[T int | int64 | float64](value, min, max T) bool

InRange 泛型版本的范围检查

func InRangeFloat64

func InRangeFloat64(value, min, max float64) bool

InRangeFloat64 检查浮点数是否在指定范围内(包含边界)

func InRangeInt

func InRangeInt(value, min, max int) bool

InRangeInt 检查整数是否在指定范围内(包含边界)

func IndexOf

func IndexOf[T comparable](arr []T, v T) int

IndexOf 返回元素首次出现的索引,未找到返回 -1

func IntToIP

func IntToIP(ipInt uint32) string

IntToIP 将32位无符号整数转换为IP地址

func Intersect

func Intersect[T comparable](a, b []T) []T

Intersect 求两个切片的交集,返回新切片

func IsAlpha

func IsAlpha(str string) bool

IsAlpha 验证是否只包含字母

func IsAlphaNumeric

func IsAlphaNumeric(str string) bool

IsAlphaNumeric 验证是否只包含字母和数字

func IsBlank

func IsBlank(str string) bool

IsBlank 检查字符串是否为空白(空或只包含空白字符)

func IsConnectionError

func IsConnectionError(err error) bool

IsConnectionError 判断是否为连接错误

func IsCurrentDST

func IsCurrentDST() bool

IsCurrentDST 判断当前是否处于夏令时

func IsDST

func IsDST(timezone string) (bool, error)

IsDST 判断指定时区是否处于夏令时

func IsDir

func IsDir(path string) bool

IsDir 检查路径是否为目录

func IsEmail

func IsEmail(str string) bool

IsEmail 验证邮箱格式

func IsEmpty

func IsEmpty(v interface{}) bool

IsEmpty 检查值是否为空(nil、空字符串、0、false等)

func IsEven

func IsEven(n int) bool

IsEven 检查是否为偶数

func IsFile

func IsFile(path string) bool

IsFile 检查路径是否为文件

func IsFloat

func IsFloat(str string) bool

IsFloat 验证是否为浮点数

func IsIP

func IsIP(str string) bool

IsIP 验证IP地址格式(支持IPv4和IPv6)

func IsIPv4

func IsIPv4(str string) bool

IsIPv4 验证IPv4地址格式

func IsIPv6

func IsIPv6(str string) bool

IsIPv6 验证IPv6地址格式

func IsInteger

func IsInteger(str string) bool

IsInteger 验证是否为整数

func IsLeapYear

func IsLeapYear(year int) bool

IsLeapYear 判断是否为闰年

func IsLocalhost

func IsLocalhost(host string) bool

IsLocalhost 检查是否为本地地址

func IsNil

func IsNil(v interface{}) bool

IsNil 检查值是否为nil

func IsNotBlank

func IsNotBlank(str string) bool

IsNotBlank 检查字符串是否不为空白

func IsNotEmpty

func IsNotEmpty(str string) bool

IsNotEmpty 检查字符串是否不为空

func IsNumeric

func IsNumeric(str string) bool

IsNumeric 验证是否为数字(整数或浮点数)

func IsOdd

func IsOdd(n int) bool

IsOdd 检查是否为奇数

func IsPhone

func IsPhone(str string) bool

IsPhone 验证手机号格式(支持中国大陆手机号)

func IsPortOpen

func IsPortOpen(host string, port int) bool

IsPortOpen 检查指定主机的端口是否开放

func IsPortOpenWithTimeout

func IsPortOpenWithTimeout(host string, port int, timeout time.Duration) bool

IsPortOpenWithTimeout 带超时的端口检测

func IsPrivateIP

func IsPrivateIP(ip string) bool

IsPrivateIP 检查是否为私有IP地址

func IsPublicIP

func IsPublicIP(ip string) bool

IsPublicIP 检查是否为公网IP地址

func IsSameDay

func IsSameDay(t1, t2 time.Time) bool

IsSameDay 判断两个时间是否为同一天

func IsTimeoutError

func IsTimeoutError(err error) bool

IsTimeoutError 判断是否为超时错误

func IsToday

func IsToday(t time.Time) bool

IsToday 判断时间是否为今天

func IsURL

func IsURL(str string) bool

IsURL 验证URL格式

func IsValidDomain

func IsValidDomain(domain string) bool

IsValidDomain 检查域名格式是否有效(简单检查)

func IsValidIP

func IsValidIP(ip string) bool

IsValidIP 检查IP地址格式是否有效

func IsValidIPv4

func IsValidIPv4(ip string) bool

IsValidIPv4 检查是否为有效的IPv4地址

func IsValidIPv6

func IsValidIPv6(ip string) bool

IsValidIPv6 检查是否为有效的IPv6地址

func IsValidJson

func IsValidJson(str string) bool

IsValidJson 检查字符串是否为有效的JSON

func IsValidPort

func IsValidPort(port int) bool

IsValidPort 检查端口号是否有效

func IsValidTimezone

func IsValidTimezone(timezone string) bool

IsValidTimezone 判断时区是否有效

func IsWeekend

func IsWeekend(t time.Time) bool

IsWeekend 判断时间是否为周末

func IsWorkday

func IsWorkday(t time.Time) bool

IsWorkday 判断时间是否为工作日

func JoinHostPort

func JoinHostPort(host string, port int) string

JoinHostPort 组合主机和端口

func JsonDecode

func JsonDecode(data string, v interface{}) error

JsonDecode 将JSON字符串解析为指定类型

func JsonDecodeFile

func JsonDecodeFile(filename string, v interface{}) error

JsonDecodeFile 从文件读取JSON并解析为指定类型

func JsonDecodeStream

func JsonDecodeStream(r io.Reader, v interface{}) error

JsonDecodeStream 从io.Reader读取JSON并解析为指定类型

func JsonEncode

func JsonEncode(v interface{}) (string, error)

JsonEncode 将任意类型转换为JSON字符串

func JsonEncodeFile

func JsonEncodeFile(v interface{}, filename string) error

JsonEncodeFile 将数据序列化为JSON并写入文件

func JsonEncodePretty

func JsonEncodePretty(v interface{}) (string, error)

JsonEncodePretty 将任意类型转换为格式化的JSON字符串

func JsonEncodeStream

func JsonEncodeStream(v interface{}, w io.Writer) error

JsonEncodeStream 将数据序列化为JSON并写入io.Writer

func JsonGetField

func JsonGetField(data string, field string) (interface{}, error)

JsonGetField 获取JSON字符串中指定字段的值

func JsonMerge

func JsonMerge(json1, json2 string) (string, error)

JsonMerge 合并两个JSON字符串

func JsonSetField

func JsonSetField(data string, field string, value interface{}) (string, error)

JsonSetField 设置JSON字符串中指定字段的值

func JsonToStruct

func JsonToStruct(data string, result interface{}) error

JsonToStruct 将JSON字符串转换为结构体

func KebabCase

func KebabCase(str string) string

KebabCase 转换为短横线命名(连字符分隔)

func LCM

func LCM(a, b int) int

LCM 计算最小公倍数

func ListDir

func ListDir(path string) ([]string, error)

ListDir 列出目录内容

func ListDirRecursive

func ListDirRecursive(path string) ([]string, error)

ListDirRecursive 递归列出目录内容

func LowerCase

func LowerCase(str string) string

LowerCase 转换为小写

func MD5

func MD5(str string) string

MD5 计算字符串的MD5值

func MD5Bytes

func MD5Bytes(data []byte) string

MD5Bytes 计算字节数组的MD5值

func MD5File

func MD5File(filePath string) (string, error)

MD5File 计算文件的MD5值

func Map

func Map[T any, R any](arr []T, f func(T) R) []R

Map 映射,返回新切片

func MapToStruct

func MapToStruct(data map[string]interface{}, result interface{}) error

MapToStruct 将map转换为结构体

func MapToStructWithTag

func MapToStructWithTag(data map[string]interface{}, result interface{}, tagName string) error

MapToStructWithTag 将map转换为结构体,使用指定的tag作为key

func Max

func Max[T int | int64 | float64](a, b T) T

Max 泛型版本的最大值函数

func MaxFloat64

func MaxFloat64(a, b float64) float64

MaxFloat64 返回两个浮点数中的最大值

func MaxInt

func MaxInt(a, b int) int

MaxInt 返回两个整数中的最大值

func MaxInt64

func MaxInt64(a, b int64) int64

MaxInt64 返回两个64位整数中的最大值

func MaxSlice

func MaxSlice[T int | int64 | float64](numbers []T) T

MaxSlice 泛型版本的数组最大值

func MaxSliceInt

func MaxSliceInt(numbers []int) int

MaxSliceInt 返回整数数组中的最大值

func Min

func Min[T int | int64 | float64](a, b T) T

Min 泛型版本的最小值函数

func MinFloat64

func MinFloat64(a, b float64) float64

MinFloat64 返回两个浮点数中的最小值

func MinInt

func MinInt(a, b int) int

MinInt 返回两个整数中的最小值

func MinInt64

func MinInt64(a, b int64) int64

MinInt64 返回两个64位整数中的最小值

func MinSlice

func MinSlice[T int | int64 | float64](numbers []T) T

MinSlice 泛型版本的数组最小值

func MinSliceInt

func MinSliceInt(numbers []int) int

MinSliceInt 返回整数数组中的最小值

func MoveFile

func MoveFile(src, dst string) error

MoveFile 移动文件

func MustBool

func MustBool(v interface{}) bool

MustBool 将任意类型转换为bool类型,转换失败返回默认值

func MustCopyStruct

func MustCopyStruct(src, dst interface{})

MustCopyStruct 强制复制结构体

func MustFloat

func MustFloat(v interface{}) float64

MustFloat 将任意类型转换为float64类型,转换失败返回默认值

func MustGetStructFieldType

func MustGetStructFieldType(obj interface{}, fieldName string) reflect.Type

MustGetStructFieldType 强制获取结构体指定字段的类型

func MustGetStructFieldValue

func MustGetStructFieldValue(obj interface{}, fieldName string) interface{}

MustGetStructFieldValue 强制获取结构体指定字段的值

func MustInt

func MustInt(v interface{}) int

MustInt 将任意类型转换为int类型,转换失败返回默认值

func MustInt64

func MustInt64(v interface{}) int64

MustInt64 将任意类型转换为int64类型,转换失败返回默认值

func MustJsonDecode

func MustJsonDecode(data string, v interface{})

MustJsonDecode 强制解码JSON字符串到指定类型

func MustJsonDecodeFile

func MustJsonDecodeFile(filename string, v interface{})

MustJsonDecodeFile 强制从文件读取JSON并解码到指定类型

func MustJsonDecodeStream

func MustJsonDecodeStream(r io.Reader, v interface{})

MustJsonDecodeStream 强制从流读取JSON并解码到指定类型

func MustJsonEncode

func MustJsonEncode(v interface{}) string

MustJsonEncode 强制将任意类型转换为JSON字符串

func MustJsonEncodeFile

func MustJsonEncodeFile(v interface{}, filename string)

MustJsonEncodeFile 强制将对象编码为JSON并保存到文件

func MustJsonEncodePretty

func MustJsonEncodePretty(v interface{}) string

MustJsonEncodePretty 强制将任意类型转换为格式化的JSON字符串

func MustJsonEncodeStream

func MustJsonEncodeStream(v interface{}, w io.Writer)

MustJsonEncodeStream 强制将对象编码为JSON并写入流

func MustJsonGetField

func MustJsonGetField(data string, field string) interface{}

MustJsonGetField 强制获取JSON字段值

func MustJsonMerge

func MustJsonMerge(json1, json2 string) string

MustJsonMerge 强制合并两个JSON字符串

func MustJsonSetField

func MustJsonSetField(data string, field string, value interface{}) string

MustJsonSetField 强制设置JSON字段值

func MustJsonToStruct

func MustJsonToStruct(data string, result interface{})

MustJsonToStruct 强制将JSON字符串转换为结构体

func MustMapToStruct

func MustMapToStruct(data map[string]interface{}, result interface{})

MustMapToStruct 强制将map转换为结构体

func MustMapToStructWithTag

func MustMapToStructWithTag(data map[string]interface{}, result interface{}, tagName string)

MustMapToStructWithTag 强制将map转换为结构体,使用指定的tag作为key

func MustSetStructFieldValue

func MustSetStructFieldValue(obj interface{}, fieldName string, value interface{})

MustSetStructFieldValue 强制设置结构体指定字段的值

func MustStructToJson

func MustStructToJson(obj interface{}) string

MustStructToJson 强制将结构体转换为JSON字符串

func MustStructToMap

func MustStructToMap(obj interface{}) map[string]interface{}

MustStructToMap 强制将结构体转换为map

func MustStructToMapWithTag

func MustStructToMapWithTag(obj interface{}, tagName string) map[string]interface{}

MustStructToMapWithTag 强制将结构体转换为map,使用指定的tag作为key

func MustType

func MustType(v interface{}, targetType string) interface{}

MustType 将任意类型转换为指定类型,转换失败返回默认值

func NewHttpClient

func NewHttpClient(config *HttpConfig) (*http.Client, error)

NewHttpClient 创建HTTP客户端

func NormalizeHost

func NormalizeHost(hostPort string) string

NormalizeHost 标准化主机地址(移除端口)

func Now

func Now() time.Time

Now 获取当前时间

func PadLeft

func PadLeft(str string, length int, pad string) string

PadLeft 在字符串左侧填充指定字符到指定长度

func PadRight

func PadRight(str string, length int, pad string) string

PadRight 在字符串右侧填充指定字符到指定长度

func ParseHostPort

func ParseHostPort(hostPort string) (host string, port int, err error)

ParseHostPort 解析主机和端口

func ParseObjectID

func ParseObjectID(objectID string) (map[string]interface{}, error)

ParseObjectID 解析ObjectID

func ParseSnowflakeID

func ParseSnowflakeID(id int64) map[string]int64

ParseSnowflakeID 解析雪花ID

func ParseTime

func ParseTime(timeStr, format string) (time.Time, error)

ParseTime 解析时间字符串

func ParseUrl

func ParseUrl(urlStr string) (*url.URL, error)

ParseUrl 解析URL

func PascalCase

func PascalCase(str string) string

PascalCase 转换为帕斯卡命名(首字母大写的驼峰)

func PasswordHash

func PasswordHash(password string) string

PasswordHash 密码哈希(使用SHA256)

func PasswordVerify

func PasswordVerify(password, hash string) bool

PasswordVerify 密码验证

func Patch

func Patch(url string, args ...interface{}) (*http.Response, error)

Patch 发送PATCH请求

func Percentage

func Percentage[T int | int64 | float64](part, total T) float64

Percentage 泛型版本的百分比计算

func PercentageFloat64

func PercentageFloat64(part, total float64) float64

PercentageFloat64 计算浮点数百分比

func PercentageInt

func PercentageInt(part, total int) float64

PercentageInt 计算整数百分比

func Ping

func Ping(host string) bool

Ping 检测主机是否可达(使用TCP连接测试)

func PingWithTimeout

func PingWithTimeout(host string, timeout time.Duration) bool

PingWithTimeout 带超时的Ping检测

func Post

func Post(url string, args ...interface{}) (*http.Response, error)

Post 发送POST请求

func PowerFloat64

func PowerFloat64(base, exp float64) float64

PowerFloat64 浮点数幂运算

func PowerInt

func PowerInt(base, exp int) int

PowerInt 整数幂运算

func PtrOrVal

func PtrOrVal[T any](ptr *T, def T) T

PtrOrVal 指针不为 nil 返回指针指向的值,否则返回默认值

func Put

func Put(url string, args ...interface{}) (*http.Response, error)

Put 发送PUT请求

func RandomBool

func RandomBool() bool

RandomBool 生成随机布尔值

func RandomBytes

func RandomBytes(n int) []byte

RandomBytes 生成指定长度的随机字节数组

func RandomElement

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

RandomElement 从切片中随机选择一个元素

func RandomElements

func RandomElements[T any](slice []T, n int) []T

RandomElements 从切片中随机选择n个元素

func RandomFloat64

func RandomFloat64(min, max float64) float64

RandomFloat64 生成指定范围内的随机float64 [min, max)

func RandomInt

func RandomInt(min, max int) int

RandomInt 生成指定范围内的随机整数 [min, max)

func RandomInt64

func RandomInt64(min, max int64) int64

RandomInt64 生成指定范围内的随机int64 [min, max)

func RandomNumberString

func RandomNumberString(n int) string

RandomNumberString 生成指定长度的随机数字字符串

func RandomSpecialString

func RandomSpecialString(n int) string

RandomSpecialString 生成指定长度的随机特殊字符字符串

func RandomString

func RandomString(n int) string

RandomString 生成指定长度的随机字符串

func RandomTime

func RandomTime(start, end time.Time) time.Time

RandomTime 生成指定时间范围内的随机时间

func RandomUUID

func RandomUUID() string

RandomUUID 生成随机UUID

func RandomWeight

func RandomWeight(weights []float64) int

RandomWeight 根据权重随机选择

func ReadCSVWithOptions

func ReadCSVWithOptions(path string, options *CSVOptions) ([][]string, error)

ReadCSVWithOptions 使用自定义选项读取CSV

func ReadExcel

func ReadExcel(path string) ([][]string, error)

ReadExcel 读取Excel文件,支持.xlsx和.csv格式

func ReadExcelSheet

func ReadExcelSheet(path string, sheetName string) ([][]string, error)

ReadExcelSheet 读取Excel文件的指定工作表

func ReadFile

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

ReadFile 读取文件内容

func ReadFileLines

func ReadFileLines(path string) ([]string, error)

ReadFileLines 按行读取文件

func ReadFileString

func ReadFileString(path string) (string, error)

ReadFileString 读取文件内容为字符串

func ReadResponse

func ReadResponse(resp *http.Response) ([]byte, error)

ReadResponse 读取响应内容

func ReadResponseJson

func ReadResponseJson(resp *http.Response, v interface{}) error

ReadResponseJson 读取响应内容为JSON

func ReadResponseString

func ReadResponseString(resp *http.Response) (string, error)

ReadResponseString 读取响应内容为字符串

func Remove

func Remove[T comparable](arr []T, v T) []T

Remove 移除所有等于 v 的元素,返回新切片

func Repeat

func Repeat(str string, count int) string

Repeat 重复字符串指定次数

func Reverse

func Reverse[T any](arr []T) []T

Reverse 反转切片,返回新切片

func ReverseString

func ReverseString(str string) string

ReverseString 反转字符串

func Round

func Round(f float64, precision int) float64

Round 四舍五入到指定精度

func SHA1

func SHA1(str string) string

SHA1 计算字符串的SHA1值

func SHA1Bytes

func SHA1Bytes(data []byte) string

SHA1Bytes 计算字节数组的SHA1值

func SHA256

func SHA256(str string) string

SHA256 计算字符串的SHA256值

func SHA256Bytes

func SHA256Bytes(data []byte) string

SHA256Bytes 计算字节数组的SHA256值

func SHA512

func SHA512(str string) string

SHA512 计算字符串的SHA512值

func SHA512Bytes

func SHA512Bytes(data []byte) string

SHA512Bytes 计算字节数组的SHA512值

func SaveConfig

func SaveConfig(c Config, filename string) error

SaveConfig 保存配置到文件

func ScanPorts

func ScanPorts(host string, startPort, endPort int) []int

ScanPorts 扫描主机的端口范围

func ScanPortsWithTimeout

func ScanPortsWithTimeout(host string, startPort, endPort int, timeout time.Duration) []int

ScanPortsWithTimeout 带超时的端口扫描

func SetStructFieldValue

func SetStructFieldValue(obj interface{}, fieldName string, value interface{}) error

SetStructFieldValue 设置结构体指定字段的值

func Shuffle

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

Shuffle 随机打乱切片

func SnakeCase

func SnakeCase(str string) string

SnakeCase 转换为蛇形命名(下划线分隔)

func Sqrt

func Sqrt(f float64) float64

Sqrt 平方根

func StartOfDay

func StartOfDay(t time.Time) time.Time

StartOfDay 获取指定时间的开始时间

func StartOfMonth

func StartOfMonth(t time.Time) time.Time

StartOfMonth 获取指定时间所在月的开始时间

func StartOfWeek

func StartOfWeek(t time.Time) time.Time

StartOfWeek 获取指定时间所在周的开始时间(周一)

func StartOfYear

func StartOfYear(t time.Time) time.Time

StartOfYear 获取指定时间所在年的开始时间

func StructToExcel

func StructToExcel(data interface{}, path string) error

StructToExcel 结构体切片转Excel

func StructToExcelWithSheet

func StructToExcelWithSheet(data interface{}, path string, sheetName string) error

StructToExcelWithSheet 结构体切片转Excel(指定工作表)

func StructToJson

func StructToJson(obj interface{}) (string, error)

StructToJson 将结构体转换为JSON字符串

func StructToMap

func StructToMap(obj interface{}) (map[string]interface{}, error)

StructToMap 将结构体转换为map

func StructToMapWithTag

func StructToMapWithTag(obj interface{}, tagName string) (map[string]interface{}, error)

StructToMapWithTag 将结构体转换为map,使用指定的tag作为key

func Sum

func Sum[T int | int64 | float64](numbers []T) T

Sum 泛型版本的求和

func SumFloat64

func SumFloat64(numbers []float64) float64

SumFloat64 计算浮点数数组的总和

func SumInt

func SumInt(numbers []int) int

SumInt 计算整数数组的总和

func Ternary

func Ternary[T any](cond bool, a, b T) T

Ternary 三元运算符函数,条件为 true 返回 a,否则返回 b

func TimeToUnix

func TimeToUnix(t time.Time) int64

TimeToUnix 时间转时间戳(秒)

func TimeToUnixMilli

func TimeToUnixMilli(t time.Time) int64

TimeToUnixMilli 时间转时间戳(毫秒)

func TitleCase

func TitleCase(str string) string

TitleCase 转换为标题格式(每个单词首字母大写)

func ToBool

func ToBool(v interface{}) (bool, error)

ToBool 将任意类型转换为bool类型

func ToChina

func ToChina(t time.Time) time.Time

ToChina 将时间转换为中国时区

func ToFloat

func ToFloat(v interface{}) (float64, error)

ToFloat 将任意类型转换为float64类型

func ToInt

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

ToInt 将任意类型转换为int类型

func ToInt64

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

ToInt64 将任意类型转换为int64类型

func ToLocal

func ToLocal(t time.Time) time.Time

ToLocal 将时间转换为本地时间

func ToLocation

func ToLocation(t time.Time, timezone string) (time.Time, error)

ToLocation 将时间转换到指定时区

func ToStr

func ToStr(v interface{}) string

ToStr 将任意类型转换为字符串

func ToType

func ToType(v interface{}, targetType string) (interface{}, error)

ToType 将任意类型转换为指定类型

func ToUTC

func ToUTC(t time.Time) time.Time

ToUTC 将时间转换为UTC时间

func Today

func Today() time.Time

Today 获取今天的开始时间

func Tomorrow

func Tomorrow() time.Time

Tomorrow 获取明天的开始时间

func Trim

func Trim(str string) string

Trim 去除字符串前后空白字符

func TrimLeft

func TrimLeft(str, cutset string) string

TrimLeft 去除字符串左侧指定字符

func TrimRight

func TrimRight(str, cutset string) string

TrimRight 去除字符串右侧指定字符

func Truncate

func Truncate(str string, length int, suffix string) string

Truncate 截断字符串到指定长度,超出部分用后缀替代

func Union

func Union[T comparable](a, b []T) []T

Union 合并两个切片并去重,返回新切片

func Unique

func Unique[T comparable](arr []T) []T

Unique 去重,返回新切片

func UnixMilliToTime

func UnixMilliToTime(timestamp int64) time.Time

UnixMilliToTime 时间戳(毫秒)转时间

func UnixToTime

func UnixToTime(timestamp int64) time.Time

UnixToTime 时间戳(秒)转时间

func UploadFile

func UploadFile(url string, fieldName, filePath string, extraFields map[string]string, config *HttpConfig) (*http.Response, error)

UploadFile 上传文件

func UpperCase

func UpperCase(str string) string

UpperCase 转换为大写

func ValidateExcelStruct

func ValidateExcelStruct(structType reflect.Type) error

ValidateExcelStruct 验证结构体是否适合Excel转换

func ValidateObjectID

func ValidateObjectID(objectID string) bool

ValidateObjectID 验证ObjectID格式

func ValidateUUID

func ValidateUUID(uuid string) bool

ValidateUUID 验证UUID格式

func WriteCSVWithOptions

func WriteCSVWithOptions(data [][]string, path string, options *CSVOptions) error

WriteCSVWithOptions 使用自定义选项写入CSV

func WriteExcel

func WriteExcel(data [][]string, path string) error

WriteExcel 写入Excel文件,根据扩展名自动选择格式

func WriteExcelSheet

func WriteExcelSheet(data [][]string, path string, sheetName string) error

WriteExcelSheet 写入Excel文件的指定工作表

func WriteFile

func WriteFile(path string, data []byte) error

WriteFile 写入文件内容

func WriteFileLines

func WriteFileLines(path string, lines []string) error

WriteFileLines 按行写入文件

func WriteFileString

func WriteFileString(path string, content string) error

WriteFileString 写入字符串到文件

func Yesterday

func Yesterday() time.Time

Yesterday 获取昨天的开始时间

Types

type AtomicBool

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

AtomicBool 原子布尔值

func NewAtomicBool

func NewAtomicBool(initial bool) *AtomicBool

NewAtomicBool 创建新的原子布尔值

func (*AtomicBool) Get

func (b *AtomicBool) Get() bool

Get 获取值

func (*AtomicBool) Set

func (b *AtomicBool) Set(value bool)

Set 设置值

type AtomicInt64

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

AtomicInt64 原子整数

func NewAtomicInt64

func NewAtomicInt64(initial int64) *AtomicInt64

NewAtomicInt64 创建新的原子整数

func (*AtomicInt64) Add

func (i *AtomicInt64) Add(delta int64) int64

Add 增加值

func (*AtomicInt64) Get

func (i *AtomicInt64) Get() int64

Get 获取值

func (*AtomicInt64) Set

func (i *AtomicInt64) Set(value int64)

Set 设置值

type Barrier

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

Barrier 屏障

func NewBarrier

func NewBarrier(parties int, timeout time.Duration) *Barrier

NewBarrier 创建新的屏障

func (*Barrier) Await

func (b *Barrier) Await() (int, error)

Await 等待所有线程到达屏障

func (*Barrier) GetNumberWaiting

func (b *Barrier) GetNumberWaiting() int

GetNumberWaiting 获取当前等待的线程数

func (*Barrier) GetParties

func (b *Barrier) GetParties() int

GetParties 获取屏障的参与线程数

func (*Barrier) IsBroken

func (b *Barrier) IsBroken() bool

IsBroken 检查屏障是否已损坏

func (*Barrier) Reset

func (b *Barrier) Reset()

Reset 重置屏障

type BasicAuth

type BasicAuth struct {
	Username string
	Password string
}

BasicAuth Basic认证信息

type CSVOptions

type CSVOptions struct {
	Comma            rune // 分隔符,默认为逗号
	Comment          rune // 注释符
	FieldsPerRecord  int  // 每条记录的字段数,-1表示可变
	LazyQuotes       bool // 是否允许懒引号
	TrimLeadingSpace bool // 是否去除前导空格
}

CSVOptions CSV读写选项

func DefaultCSVOptions

func DefaultCSVOptions() *CSVOptions

DefaultCSVOptions 默认CSV选项

type Config

type Config interface {
	Get(key string) interface{}
	GetString(key string) string
	GetInt(key string) int
	GetInt64(key string) int64
	GetFloat(key string) float64
	GetBool(key string) bool
	GetStringSlice(key string) []string
	GetStringMap(key string) map[string]interface{}
	Set(key string, value interface{})
	All() map[string]interface{}
}

Config 配置接口

func LoadConfig

func LoadConfig(filename string) (Config, error)

LoadConfig 加载配置文件

func NewConfig

func NewConfig() Config

NewConfig 创建配置实例

type ConnectionTest

type ConnectionTest struct {
	Host     string        `json:"host"`
	Port     int           `json:"port"`
	Protocol string        `json:"protocol"`
	Success  bool          `json:"success"`
	Duration time.Duration `json:"duration"`
	Error    string        `json:"error,omitempty"`
}

TestConnection 测试网络连接

func BatchTestConnections

func BatchTestConnections(hosts []string, ports []int) []ConnectionTest

BatchTestConnections 批量测试连接

func TestTCPConnection

func TestTCPConnection(host string, port int) ConnectionTest

TestTCPConnection 测试TCP连接

func TestUDPConnection

func TestUDPConnection(host string, port int) ConnectionTest

TestUDPConnection 测试UDP连接

type ExcelInfo

type ExcelInfo struct {
	Path      string   `json:"path"`
	Sheets    []string `json:"sheets"`
	TotalRows int      `json:"total_rows"`
	TotalCols int      `json:"total_cols"`
	FileSize  int64    `json:"file_size"`
	ModTime   string   `json:"mod_time"`
}

ExcelInfo Excel文件信息

func GetExcelInfo

func GetExcelInfo(path string) (*ExcelInfo, error)

GetExcelInfo 获取Excel文件信息

type HttpConfig

type HttpConfig struct {
	Timeout     time.Duration     // 超时时间
	RetryTimes  int               // 重试次数
	RetryDelay  time.Duration     // 重试延迟
	Headers     map[string]string // 请求头
	Cookies     []*http.Cookie    // Cookie
	Proxy       string            // 代理地址
	Insecure    bool              // 是否跳过SSL验证
	UserAgent   string            // User-Agent
	BasicAuth   *BasicAuth        // Basic认证
	MaxRedirect int               // 最大重定向次数
}

HttpConfig HTTP请求配置

type Mutex

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

Mutex 增强版的 sync.Mutex,支持超时

func NewMutex

func NewMutex(timeout time.Duration) *Mutex

NewMutex 创建新的互斥锁

func (*Mutex) Lock

func (m *Mutex) Lock() error

Lock 加锁,支持超时

func (*Mutex) Unlock

func (m *Mutex) Unlock()

Unlock 解锁

type NetworkInterface

type NetworkInterface struct {
	Name         string   `json:"name"`
	HardwareAddr string   `json:"hardware_addr"`
	Flags        string   `json:"flags"`
	MTU          int      `json:"mtu"`
	IPs          []string `json:"ips"`
}

NetworkInterface 网络接口信息结构

func GetNetworkInterfaces

func GetNetworkInterfaces() []NetworkInterface

GetNetworkInterfaces 获取网络接口信息

type ObjectIDGenerator

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

ObjectIDGenerator ObjectID生成器

func (*ObjectIDGenerator) Generate

func (g *ObjectIDGenerator) Generate() string

Generate 生成ObjectID

type Once

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

Once 增强版的 sync.Once,支持重置

func (*Once) Do

func (o *Once) Do(f func())

Do 执行函数,确保只执行一次

func (*Once) Reset

func (o *Once) Reset()

Reset 重置 Once,允许再次执行

type Pool

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

Pool 协程池

func NewPool

func NewPool(workers int) *Pool

NewPool 创建新的协程池

func (*Pool) Start

func (p *Pool) Start()

Start 启动协程池

func (*Pool) Stop

func (p *Pool) Stop()

Stop 停止协程池

func (*Pool) Submit

func (p *Pool) Submit(task func()) error

Submit 提交任务到协程池

type RWMutex

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

RWMutex 增强版的 sync.RWMutex,支持超时

func NewRWMutex

func NewRWMutex(timeout time.Duration) *RWMutex

NewRWMutex 创建新的读写锁

func (*RWMutex) Lock

func (m *RWMutex) Lock() error

Lock 写锁,支持超时

func (*RWMutex) RLock

func (m *RWMutex) RLock() error

RLock 读锁,支持超时

func (*RWMutex) RUnlock

func (m *RWMutex) RUnlock()

RUnlock 读解锁

func (*RWMutex) Unlock

func (m *RWMutex) Unlock()

Unlock 写解锁

type Semaphore

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

Semaphore 信号量

func NewSemaphore

func NewSemaphore(size int) *Semaphore

NewSemaphore 创建新的信号量

func (*Semaphore) Acquire

func (s *Semaphore) Acquire() error

Acquire 获取信号量

func (*Semaphore) Count

func (s *Semaphore) Count() int

Count 获取当前信号量计数

func (*Semaphore) Release

func (s *Semaphore) Release() error

Release 释放信号量

func (*Semaphore) Size

func (s *Semaphore) Size() int

Size 获取信号量大小

func (*Semaphore) TryAcquire

func (s *Semaphore) TryAcquire(timeout time.Duration) error

TryAcquire 尝试获取信号量,支持超时

type SnowflakeGenerator

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

SnowflakeGenerator 雪花ID生成器

func NewSnowflakeGenerator

func NewSnowflakeGenerator(workerID, datacenterID int64) (*SnowflakeGenerator, error)

NewSnowflakeGenerator 创建雪花ID生成器

func (*SnowflakeGenerator) Generate

func (s *SnowflakeGenerator) Generate() int64

Generate 生成雪花ID

type WaitGroup

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

WaitGroup 增强版的 WaitGroup,支持超时和取消

func NewWaitGroup

func NewWaitGroup(ctx context.Context, timeout time.Duration) *WaitGroup

NewWaitGroup 创建新的 WaitGroup

func (*WaitGroup) Add

func (wg *WaitGroup) Add(delta int)

Add 添加等待计数

func (*WaitGroup) Done

func (wg *WaitGroup) Done()

Done 完成一个任务

func (*WaitGroup) Wait

func (wg *WaitGroup) Wait() error

Wait 等待所有任务完成,支持超时和取消

Jump to

Keyboard shortcuts

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