utils

package
v1.3.3 Latest Latest
Warning

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

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

README

Utils - 工具函数库

概述

Utils是一个综合性的工具函数库,包含加密、缓存、网络、数据库、同步、文件操作等各类常用功能。为应用程序开发提供基础的工具支持。

主要功能

1. 加密工具 (aes.go)
  • AES加密/解密
  • Base64编码
  • 密钥管理
2. 缓存系统 (lrucache.go)
  • LRU缓存实现
  • 过期时间管理
  • 线程安全操作
3. GUID/UUID (guid.go, uuid.go)
  • GUID生成和解析
  • UUID生成
  • Windows GUID支持
4. 网络工具 (net_utils.go)
  • IP地址处理
  • 网络连接检测
  • URL处理工具
5. 数据库工具 (db_utils.go)
  • 数据库连接管理
  • SQL工具函数
  • 事务处理辅助
6. 同步工具 (sync_helper.go)
  • 并发控制工具
  • 同步原语封装
  • 协程管理
7. 单例模式 (singleton.go)
  • 单例模式实现
  • 线程安全单例
  • 延迟初始化
8. 堆栈工具 (stack.go)
  • 调用堆栈获取
  • 错误追踪
  • 调试信息
9. 通用辅助 (helper.go)
  • 文件操作
  • 字符串处理
  • 类型转换
  • 时间处理

使用示例

AES加密
package main

import (
    "fmt"
    "path/to/utils"
)

func main() {
    key := "your-secret-key"
    plaintext := "hello world"
    
    // 加密
    encrypted, err := utils.AESEncrypt(plaintext, key)
    if err != nil {
        fmt.Printf("加密失败: %v\n", err)
        return
    }
    
    // 解密
    decrypted, err := utils.AESDecrypt(encrypted, key)
    if err != nil {
        fmt.Printf("解密失败: %v\n", err)
        return
    }
    
    fmt.Printf("原文: %s\n", plaintext)
    fmt.Printf("密文: %s\n", encrypted)
    fmt.Printf("解密: %s\n", decrypted)
}
LRU缓存
package main

import (
    "fmt"
    "time"
    "path/to/utils"
)

func main() {
    // 创建容量为100的LRU缓存
    cache := utils.NewLRUCache(100)
    
    // 设置缓存项
    cache.Set("key1", "value1", time.Minute*5)
    cache.Set("key2", "value2", time.Hour)
    
    // 获取缓存项
    if value, ok := cache.Get("key1"); ok {
        fmt.Printf("缓存值: %s\n", value)
    }
    
    // 检查缓存
    if cache.Contains("key2") {
        fmt.Println("key2 存在于缓存中")
    }
    
    // 删除缓存项
    cache.Delete("key1")
    
    // 清空缓存
    cache.Clear()
}
GUID操作
package main

import (
    "fmt"
    "path/to/utils"
)

func main() {
    // 生成新GUID
    guid := utils.NewGUID()
    fmt.Printf("新GUID: %s\n", guid.String())
    
    // 解析GUID字符串
    guidStr := "{12345678-1234-5678-9ABC-DEF012345678}"
    parsedGuid, err := utils.ParseGUID(guidStr)
    if err != nil {
        fmt.Printf("解析失败: %v\n", err)
        return
    }
    
    fmt.Printf("解析的GUID: %s\n", parsedGuid.String())
}
网络工具
package main

import (
    "fmt"
    "path/to/utils"
)

func main() {
    // 检查网络连接
    if utils.IsNetworkAvailable() {
        fmt.Println("网络连接可用")
    }
    
    // 获取本机IP
    ip, err := utils.GetLocalIP()
    if err != nil {
        fmt.Printf("获取IP失败: %v\n", err)
        return
    }
    fmt.Printf("本机IP: %s\n", ip)
    
    // 验证IP地址
    if utils.IsValidIP("192.168.1.1") {
        fmt.Println("IP地址有效")
    }
}
文件操作
package main

import (
    "fmt"
    "path/to/utils"
)

func main() {
    // 检查文件存在
    if utils.FileExists("test.txt") {
        fmt.Println("文件存在")
    }
    
    // 创建目录
    err := utils.CreateDir("./data")
    if err != nil {
        fmt.Printf("创建目录失败: %v\n", err)
    }
    
    // 获取文件大小
    size, err := utils.GetFileSize("test.txt")
    if err != nil {
        fmt.Printf("获取文件大小失败: %v\n", err)
    } else {
        fmt.Printf("文件大小: %d bytes\n", size)
    }
    
    // 复制文件
    err = utils.CopyFile("source.txt", "dest.txt")
    if err != nil {
        fmt.Printf("复制文件失败: %v\n", err)
    }
}
字符串处理
package main

import (
    "fmt"
    "path/to/utils"
)

func main() {
    // 生成随机字符串
    randomStr := utils.RandomString(10)
    fmt.Printf("随机字符串: %s\n", randomStr)
    
    // 字符串转换
    result := utils.ToCamelCase("hello_world")
    fmt.Printf("驼峰命名: %s\n", result)
    
    // 字符串截取
    truncated := utils.TruncateString("这是一个很长的字符串", 10)
    fmt.Printf("截取字符串: %s\n", truncated)
    
    // MD5哈希
    hash := utils.MD5Hash("hello world")
    fmt.Printf("MD5哈希: %s\n", hash)
}
时间处理
package main

import (
    "fmt"
    "time"
    "path/to/utils"
)

func main() {
    // 格式化时间
    now := time.Now()
    formatted := utils.FormatTime(now, "2006-01-02 15:04:05")
    fmt.Printf("格式化时间: %s\n", formatted)
    
    // 解析时间字符串
    timeStr := "2023-12-25 10:30:00"
    parsedTime, err := utils.ParseTime(timeStr, "2006-01-02 15:04:05")
    if err != nil {
        fmt.Printf("时间解析失败: %v\n", err)
    } else {
        fmt.Printf("解析时间: %s\n", parsedTime.String())
    }
    
    // 时间差计算
    duration := utils.TimeSince(parsedTime)
    fmt.Printf("时间差: %s\n", duration.String())
}
单例模式
package main

import (
    "fmt"
    "path/to/utils"
)

type Config struct {
    AppName string
    Version string
}

var configInstance *Config

func GetConfig() *Config {
    return utils.GetSingleton(&configInstance, func() *Config {
        return &Config{
            AppName: "MyApp",
            Version: "1.0.0",
        }
    }).(*Config)
}

func main() {
    config1 := GetConfig()
    config2 := GetConfig()
    
    fmt.Printf("配置1: %+v\n", config1)
    fmt.Printf("配置2: %+v\n", config2)
    fmt.Printf("是同一个实例: %t\n", config1 == config2)
}

常用常量

// 时间格式
const (
    DateTimeFormat = "2006-01-02 15:04:05"
    DateFormat     = "2006-01-02"
    TimeFormat     = "15:04:05"
)

// 文件大小单位
const (
    KB = 1024
    MB = KB * 1024
    GB = MB * 1024
    TB = GB * 1024
)

性能优化

  1. 缓存使用: 合理使用LRU缓存减少重复计算
  2. 字符串处理: 使用strings.Builder进行字符串拼接
  3. 并发控制: 使用sync_helper中的工具进行并发控制
  4. 内存管理: 及时释放不再使用的资源

注意事项

  1. 线程安全: 标记了线程安全的函数可以并发使用
  2. 错误处理: 所有可能失败的操作都返回error
  3. 资源清理: 使用完毕后及时清理资源
  4. 配置验证: 传入参数需要进行有效性验证

适用场景

  • Web应用开发
  • API服务开发
  • 系统工具开发
  • 数据处理程序
  • 网络服务程序

Utils包提供了开发中常用的基础工具,可以显著提高开发效率和代码质量。

Documentation

Index

Constants

View Source
const (
	ObjectGUIDAttribute = "objectGUID"
)

Variables

View Source
var DateFormat string = "2006-01-02"
View Source
var DateTimeFormat string = "2006-01-02 15:04:05"
View Source
var ErrInvalidID = errors.New("无效的ID")
View Source
var KeyID = "rfoMzV4D8O9owOET33vJ"
View Source
var LineEnding string // 根据系统自动设置
View Source
var MyTitle = `
===============================
作者:tea4go
邮箱:lqq1119@sina.com
===============================
`
View Source
var TimeFormat string = "15:04:05"
View Source
var TimeLocation *time.Location

Functions

func AesDecrypt

func AesDecrypt(key, test_str string) (string, error)

func AesEncrypt

func AesEncrypt(key, test_str string) (string, error)

func Base64Decode

func Base64Decode(test_str string) (string, error)

func Base64Encode

func Base64Encode(test_str string) string

func DosName

func DosName(str string) string

prepare-commit-~.sampl

func FileIsExist

func FileIsExist(filename string) bool

func GetAllIPAdress added in v1.1.3

func GetAllIPAdress() string

func GetAllMacAdress added in v1.1.3

func GetAllMacAdress() string

func GetCallStack

func GetCallStack() (level int, stack string, file string, line int)

func GetCurrentPath

func GetCurrentPath() string

获取当前程序工作目录

func GetDebugStack

func GetDebugStack() string

func GetFileBaseName

func GetFileBaseName(path string) string

Name returns the last element of path without file extension. Example: /var/www/file.js -> file file.js -> file

func GetFileDir

func GetFileDir(path string) string

Dir returns all but the last element of path, typically the path's directory. After dropping the final element, Dir calls Clean on the path and trailing slashes are removed. If the `path` is empty, Dir returns ".". If the `path` is ".", Dir treats the path as current working directory. If the `path` consists entirely of separators, Dir returns a single separator. The returned path does not end in a separator unless it is the root directory.

func GetFileExt

func GetFileExt(path string) string

Ext 返回路径使用的文件扩展名。 扩展名是从最后一个点开始的后缀 在路径的最后一个元素中; 如果有,则为空 没有点。

注意:结果包含符号'.'

func GetFileExtName

func GetFileExtName(path string) string

ExtName 类似于函数 Ext,它返回 path 使用的文件扩展名, 但结果不包含符号'.'

func GetFileModTime

func GetFileModTime(filename string) (time.Time, error)

获取文件修改时间 返回unix时间戳

func GetFileName

func GetFileName(path string) string

Basename returns the last element of path, which contains file extension. Trailing path separators are removed before extracting the last element. If the path is empty, Base returns ".". If the path consists entirely of separators, Basename returns a single separator. Example: /var/www/file.js -> file.js file.js -> file.js

func GetFileRealPath

func GetFileRealPath(path string) string

RealPath converts the given <path> to its absolute path and checks if the file path exists. If the file does not exist, return an empty string.

func GetFileSize

func GetFileSize(filename string) int64

func GetFloatSize

func GetFloatSize(fBytes float64) string

func GetFullFileName

func GetFullFileName(filename string) string

得到全路径名称,从当前目录,可执行程序目录,PATH目录查文件,如果找不到则返回传入文件名。

func GetIPAdress

func GetIPAdress() string

func GetInt64Size

func GetInt64Size(iBytes int64) string

func GetIntSize

func GetIntSize(iBytes int) string

func GetJson

func GetJson(object interface{}) string

func GetLastYear

func GetLastYear() time.Time

func GetMapByBool

func GetMapByBool(mapi map[string]string, name string, default_value bool) bool

func GetMapByInt

func GetMapByInt(mapi map[string]string, name string, default_value int) int

func GetMapByString

func GetMapByString(mapi map[string]string, name, default_value string) string

func GetNetError

func GetNetError(err error) string

在日志库里有一个相同代码,需要同步修改。

func GetNow

func GetNow() time.Time

func GetPKCS1Key added in v1.1.6

func GetPKCS1Key() (string, string, error)

生成密钥对文件,返回私钥和公钥字符串

func GetShowKey

func GetShowKey(key string) string

获取显示的AppKey

func GetShowPassword

func GetShowPassword(password string) string

获取显示的密码(只显示头尾)

func GetStatusCode

func GetStatusCode(resp *http.Response) int

func GetStringSize

func GetStringSize(sBytes string) string

func GetTimeAgo

func GetTimeAgo(t time.Time) string

func GetTimeText

func GetTimeText(fBytes int) string

func GetUInt64Size

func GetUInt64Size(iBytes uint64) string

func IIF

func IIF(b bool, t, f interface{}) interface{}

func IIFByTime

func IIFByTime(flag bool, A, B time.Time) time.Time

func IIFbyInt

func IIFbyInt(flag bool, A, B int) int

func IIFbyString

func IIFbyString(flag bool, A, B string) string

func If

func If(condition bool, trueVal, falseVal interface{}) interface{}

func IsAddrInUse added in v1.0.3

func IsAddrInUse(err error) bool

func IsAscii

func IsAscii(text_str string) bool

func IsChinese

func IsChinese(str string) bool

func IsDir

func IsDir(filename string) (bool, error)

func IsExeFile

func IsExeFile(path string) (bool, error)

是否可执行文件(linux就是x权限,win就是.exe)

func IsHanZi

func IsHanZi(text_str string) bool

func IsNetClose added in v1.0.9

func IsNetClose(err error) bool

func IsNumber

func IsNumber(text_str string) bool

func LoadFileText

func LoadFileText(file_name string) (string, error)

func LoadJson

func LoadJson(json_file string, save_object interface{}) error

save_object对象一定是指针

func Md5

func Md5(test_str string) string

func Mkdir

func Mkdir(path string) error

Mkdir creates directories recursively with given <path>. The parameter <path> is suggested to be an absolute path instead of relative one.

func ParsePriKeyBytes added in v1.1.6

func ParsePriKeyBytes(pri_key []byte) (*rsa.PrivateKey, error)

将PEM格式的私钥转换为可用于验证JWT签名的RSA公钥对象。

func ParsePubKeyBytes added in v1.1.6

func ParsePubKeyBytes(pub_key []byte) (*rsa.PublicKey, error)

将PEM格式的公钥转换为可用于验证JWT签名的RSA公钥对象。

func ParseTemplateFile

func ParseTemplateFile(wr io.Writer, tplname string, data interface{}) error

模版解析(单文件)

func ParseTemplates

func ParseTemplates(wr io.Writer, tplname string, data interface{}) error

模版解析(可带子模板)

func ReadMachineID

func ReadMachineID(size int) []byte

获得主机ID

func Round

func Round(val float64, places int) float64

func RunFileName

func RunFileName() string

获取当前程序名称

func RunPathName

func RunPathName() string

获取当前程序工作目录

func SQLExecDDL

func SQLExecDDL(db_in *sql.DB, run_sql string, ignore bool) (err error)

执行DDL语句,Oracle驱动不支持执行多个SQL语句,MySQL可以。需要拆分执行。

func SQLGetValue

func SQLGetValue(db_in *sql.DB, query_sql string, v ...interface{}) (interface{}, error)

func SQLGetValueByInt

func SQLGetValueByInt(db_in *sql.DB, query_sql string, v ...interface{}) (bool, int, error)

func SQLGetValueByString

func SQLGetValueByString(db_in *sql.DB, query_sql string, v ...interface{}) (string, error)

func SQLGetValueByTime

func SQLGetValueByTime(db_in *sql.DB, query_sql string, v ...interface{}) (time.Time, error)

func SQLGetValues

func SQLGetValues(db_in *sql.DB, query_sql string, v ...interface{}) ([]interface{}, error)

func SQLPrepared

func SQLPrepared(db_in *sql.DB, query_sql string, v ...interface{}) ([]*sql.ColumnType, error)

func SQLQuery

func SQLQuery(db_in *sql.DB, query_sql string, v ...interface{}) ([][]string, error)

func SQLQueryPrint

func SQLQueryPrint(db_in *sql.DB, query_sql string, v ...interface{}) error

func SQLRowPrintByResult

func SQLRowPrintByResult(query *sql.Rows) error

func SQLRunByInsert

func SQLRunByInsert(db_in *sql.DB, run_sql string, v ...interface{}) (int64, error)

func SQLRunByUpdate

func SQLRunByUpdate(db_in *sql.DB, run_sql string, v ...interface{}) (int64, error)

func SaveJson

func SaveJson(json_file string, save_object interface{}) error

func SetJson

func SetJson(json_text string, save_object interface{}) error

save_object对象一定是指针

func SetRunFileName

func SetRunFileName(file string) string

func StringToTime

func StringToTime(data_str string) (time.Time, error)

func StringToTimeByTemplates

func StringToTimeByTemplates(tm, templates string) (time.Time, error)

func Substr

func Substr(str string, start, length int) string

func TxRunByInsert

func TxRunByInsert(db_in *sql.Tx, run_sql string, v ...interface{}) (int64, error)

func TxRunByUpdate

func TxRunByUpdate(db_in *sql.Tx, run_sql string, v ...interface{}) (int64, error)

Types

type Glimit

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

func SetNumGoroutine

func SetNumGoroutine(n int) *Glimit

initialization Glimit struct

func (*Glimit) Run

func (g *Glimit) Run(f func())

Run f in a new goroutine but with limit.

type ISingleton

type ISingleton interface {
	// Return the encapsulated singleton
	GetSingleton() (interface{}, error)
}

接口,用于访问单一对象

func NewSingleton

func NewSingleton(init SingletonInitFunc) ISingleton

type JsonTime

type JsonTime time.Time

func (JsonTime) FromString

func (Self JsonTime) FromString(data string) error

func (JsonTime) MarshalJSON

func (Self JsonTime) MarshalJSON() ([]byte, error)

实现它的json序列化方法

func (JsonTime) ToString

func (Self JsonTime) ToString() string

func (JsonTime) UnmarshalJSON

func (Self JsonTime) UnmarshalJSON(data []byte, v interface{}) error

type SingletonInitFunc

type SingletonInitFunc func() (interface{}, error)

type TAESEncrypt

type TAESEncrypt struct {
	Key     []byte
	IV      []byte
	ZeroPad bool
}

func (*TAESEncrypt) Decrypt

func (this *TAESEncrypt) Decrypt(ciphertext string) ([]byte, error)

func (*TAESEncrypt) Encrypt

func (this *TAESEncrypt) Encrypt(strMesg string) ([]byte, error)

func (*TAESEncrypt) Init

func (this *TAESEncrypt) Init(key_str string)

func (*TAESEncrypt) PKCS5Padding

func (this *TAESEncrypt) PKCS5Padding(ciphertext []byte, blockSize int) []byte

func (*TAESEncrypt) PKCS5UnPadding

func (this *TAESEncrypt) PKCS5UnPadding(ciphertext []byte, blockSize int) []byte

func (*TAESEncrypt) ZeroPadding

func (this *TAESEncrypt) ZeroPadding(ciphertext []byte, blockSize int) []byte

func (*TAESEncrypt) ZeroUnPadding

func (this *TAESEncrypt) ZeroUnPadding(ciphertext []byte, blockSize int) []byte

type TGUID

type TGUID struct {
	Data1 uint32
	Data2 uint16
	Data3 uint16
	Data4 [8]byte
}

GUID represents a GUID/UUID. It has the same structure as golang.org/x/sys/windows.GUID so that it can be used with functions expecting that type. Reference: https://github.com/Microsoft/go-winio/blob/v0.4.14/pkg/guid/guid.go

func GUIDFromBytes

func GUIDFromBytes(bs []byte) TGUID

FromWindowsArray constructs a GUID from a Windows encoding array of bytes.

func GUIDFromString

func GUIDFromString(s string) (TGUID, error)

FromString parses a string containing a GUID and returns the GUID. The only format currently supported is the `xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx` format.

func GUIDFromWindowsArray

func GUIDFromWindowsArray(b [16]byte) TGUID

FromWindowsArray constructs a GUID from a Windows encoding array of bytes.

func (TGUID) OctetString

func (g TGUID) OctetString() string

OctetString parses a GUID to octet string in Windows encoding. Format supported for AD(ObjectGUID Attribute) search is `\xx\xx\xx\xx\xx\xx\xx\xx\xx\xx\xx\xx\xx\xx\xx\xx`

func (TGUID) String

func (g TGUID) String() string

func (TGUID) ToWindowsArray

func (g TGUID) ToWindowsArray() [16]byte

ToWindowsArray returns an array of 16 bytes representing the GUID in Windows encoding.

type TLruCache

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

func NewLruCache

func NewLruCache(maxSize int) *TLruCache

func (*TLruCache) ClearAll

func (this *TLruCache) ClearAll()

func (*TLruCache) Delete

func (this *TLruCache) Delete(key string)

func (*TLruCache) Get

func (this *TLruCache) Get(key string) interface{}

func (*TLruCache) IsExist

func (this *TLruCache) IsExist(key string) bool

func (*TLruCache) Len

func (this *TLruCache) Len() int

func (*TLruCache) Set

func (this *TLruCache) Set(key string, val interface{}, timeout int64)

type TSingleton

type TSingleton struct {
	sync.Mutex
	// contains filtered or unexported fields
}

func (*TSingleton) GetSingleton

func (s *TSingleton) GetSingleton() (interface{}, error)

type TSize

type TSize float64
const (
	KB TSize = 1 << (10 * iota)
	MB
	GB
	TB
	PB
	EB
)

func (TSize) String

func (b TSize) String() string

type TStack

type TStack struct {
	Element []string
}

func NewStack

func NewStack() *TStack

func (*TStack) Empty

func (stack *TStack) Empty() bool

是否为空

func (*TStack) Find

func (stack *TStack) Find(value string) bool

func (*TStack) Get

func (stack *TStack) Get(idx int) (value interface{})

返回指定索引的元素

func (*TStack) Pop

func (stack *TStack) Pop() (err error)

返回下一个元素,并从Stack移除元素

func (*TStack) PopByValue

func (stack *TStack) PopByValue(value string) (err error)

返回下一个元素,并从Stack移除元素

func (*TStack) Print

func (stack *TStack) Print()

打印

func (*TStack) Push

func (stack *TStack) Push(value string)

func (*TStack) Set

func (stack *TStack) Set(idx int, value string) (err error)

修改指定索引的元素

func (*TStack) Size

func (stack *TStack) Size() int

Stack的size

func (*TStack) Swap

func (stack *TStack) Swap(other *TStack)

交换值

func (*TStack) Top

func (stack *TStack) Top() (value string)

返回下一个元素

type TUUID

type TUUID [rawLen]byte

保证每秒/每个主机/进程有16,777,216(24位)唯一ID - 4字节秒数, - 3字节机器标识符, - 2字节进程ID, - 3字节计数器,以随机值开头。

func NewUUID

func NewUUID() *TUUID

func UUIDFromString

func UUIDFromString(id string) (*TUUID, error)

func (TUUID) GetMachine

func (id TUUID) GetMachine() []byte

func (TUUID) GetPID

func (id TUUID) GetPID() uint16

func (TUUID) GetTime

func (id TUUID) GetTime() time.Time

func (TUUID) MarshalText

func (id TUUID) MarshalText() ([]byte, error)

func (TUUID) String

func (id TUUID) String() string

func (*TUUID) UnmarshalText

func (id *TUUID) UnmarshalText(text []byte) error

Jump to

Keyboard shortcuts

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