gotool

package module
v0.0.0-...-6e59f85 Latest Latest
Warning

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

Go to latest
Published: Apr 16, 2025 License: MIT Imports: 35 Imported by: 0

README

GoTool

一个轻量级的Go语言工具库,提倡的核心理念为:基于Golang原生库、无第三方依赖。

安装

go get -u github.com/up-zero/gotool

快速开始

例如 Md5() 方法,使用方式如下所示,其它方法参考功能列表及其测试案例。

package main

import "github.com/up-zero/gotool"
import "log"

func main() {
	data, err := gotool.Md5("123456") // e10adc3949ba59abbe56e057f20f883e
	if err != nil {
		log.Fatalln(err)
	}
	log.Println(data)
}

方法列表

文件
  • FileCopy 文件拷贝
  • FileMove 文件移动
  • FileDownload 文件下载
  • FileDownloadWithNotify 带通知的文件下载
  • DirCopy 绝对目录文件拷贝
  • CurrentDirCount 当前文件夹下(不迭代子文件夹)文件或文件夹的个数
  • MkParentDir 创建父级文件夹
  • FileCount 获取指定目录下的文件个数
  • FileMainName 获取指定路径的文件名
  • FileSave 保存文件
  • FileSync 文件同步
  • FileRead 读文件(结构体)
  • Zip 文件夹压缩
  • ZipWithNotify 带通知的文件夹压缩
  • Unzip 文件解压
  • UnzipWithNotify 带通知的文件解压
加解密
  • Md5 获取md5值
  • Md5Iterations 迭代多次求md5
  • Md5File 获取文件的MD5
  • HmacSHA256 计算 SHA256
  • HmacSHA384 计算 HmacSHA384
  • HmacSHA512 计算 HmacSHA512
  • JWTGenerate 生成JWT
  • JWTParse 解析JWT
类型转换
  • StrToInt8 字符串转换为int8
  • StrToInt16 字符串转换为int16
  • StrToInt32 字符串转换为int32
  • StrToInt64 字符串转换为int64
  • StrToUint8 字符串转换为uint8
  • StrToUint16 字符串转换为uint16
  • StrToUint32 字符串转换为uint32
  • StrToUint64 字符串转换为uint64
  • StrToFloat32 字符串转换为float32
  • StrToFloat64 字符串转换为float64
  • Int64ToStr int64转换为字符串
  • Uint64ToStr uint64转换为字符串
  • Float64ToStr float64转换为字符串
  • Int64ToHex int64转换为十六进制字符串
  • HexToInt64 十六进制字符串转换为int64
  • CopyProperties 复制结构体的属性
数学
  • RandomStr 随机字符串
  • RandomNumber 随机数字
  • RandomAlpha 随机字母
  • RandomAlphaNumber 随机字母数字
  • RandomRangeInt 指定范围内的随机数 [最小值, 最大值)
  • MathAbs 绝对值
  • MathMin 最小值
  • MathMax 最大值
网络
  • SendMail 发送邮件
  • Ipv4sLocal 获取本地ipv4地址
  • ShouldBindJson json入参绑定
  • ShouldBindQuery query入参绑定
  • UrlBase 获取URL路径的基础名称
  • HttpGet http get 请求
  • HttpPost http post 请求
  • HttpPut http put 请求
  • HttpDelete http delete 请求
  • HttpGetWithTimeout 带超时时间的 http get 请求
  • HttpPostWithTimeout 带超时时间的 http post 请求
  • HttpPutWithTimeout 带超时时间的 http put 请求
  • HttpDeleteWithTimeout 带超时时间的 http delete 请求
  • ParseResponse 解析响应结果
系统
  • ExecShell 运行shell命令或脚本
  • ExecCommand 运行命令
  • ExecShellWithNotify 带通知的运行shell命令或脚本
  • ExecCommandWithNotify 带通知的运行命令
  • PsByName 根据程序名查询进程列表
  • CPUTemperatures 获取CPU温度
  • SysUptime 系统启动时间
日期&时间
  • RFC3339ToNormalTime RFC3339 日期格式标准化
  • RFC1123ToNormalTime RFC1123 日期格式标准化
唯一ID
  • UUID uuid
  • UUIDGenerate 生成UUID
  • SignalSnowflake 单节点的雪花码
数组
  • ArrayDuplicate 数组去重
  • ArrayIn 数组是否包含某个值
  • ArrayJoin 整型拼接
图片
  • ImageCompression 图片压缩
  • ImageSize 图片尺寸
  • GenerateCaptcha 验证码图片生成
条件判断
  • If 三元运算符
  • NewStream 初始化 Stream
  • Filter 数据过滤
  • Map 数据处理
  • StreamMap 数据处理与转换
  • Max 数据最大值

Documentation

Index

Constants

View Source
const (
	DateTime = "2006-01-02 15:04:05"
	DateOnly = "2006-01-02"
	TimeOnly = "15:04:05"
)

Variables

View Source
var (
	// Mac 地址
	Mac string
	// EmptyMapBytes 空map
	EmptyMapBytes = []byte{0x7b, 0x7d}
	// DateTimeMilli 毫秒格式时间
	DateTimeMilli = "2006-01-02 15:04:05.000"
)
View Source
var ErrDstMustBePointerStruct = errors.New("dst must be a pointer struct")

ErrDstMustBePointerStruct 目标必须是指针结构体

View Source
var ErrDstSrcSame = errors.New("dst and src is same")

ErrDstSrcSame 目标和源是同一个

View Source
var ErrExpiredJwt = errors.New("expired jwt")

ErrExpiredJwt jwt 过期

View Source
var ErrInvalidJwtAlgorithm = errors.New("invalid jwt algorithm")

ErrInvalidJwtAlgorithm jwt 算法不支持

View Source
var ErrInvalidJwtFormat = errors.New("invalid jwt format")

ErrInvalidJwtFormat jwt 格式错误

View Source
var ErrInvalidJwtSignature = errors.New("invalid jwt signature")

ErrInvalidJwtSignature jwt 签名错误

View Source
var ErrInvalidUptimeFile = errors.New("invalid uptime file")

ErrInvalidUptimeFile uptime 文件无效

View Source
var ErrNotIsDir = errors.New("not is dir")

ErrNotIsDir 不是目录

View Source
var ErrNotSupportFormat = errors.New("not support format")

ErrNotSupportFormat 数据格式不支持

View Source
var ErrNotSupportType = errors.New("not support type")

ErrNotSupportType 不支持的类型

View Source
var ErrSrcDstCannotBeNil = errors.New("src and dst cannot be nil")

ErrSrcDstCannotBeNil 源和目标不能为空

View Source
var ImageExtMap = map[string]struct{}{
	".jpg":  {},
	".jpeg": {},
	".png":  {},
	".gif":  {},
	".bmp":  {},
	".webp": {},
	".tif":  {},
	".tiff": {},
}

Functions

func ArrayDuplicate

func ArrayDuplicate[T Number | string](elems ...[]T) []T

ArrayDuplicate 数组去重

elems 传入同种类型数组

func ArrayIn

func ArrayIn[T Number | string | bool](target T, arr []T) bool

ArrayIn 数组是否包含某个值

target 目标值 arr 待遍历的数组

func ArrayJoin

func ArrayJoin[T int | int8 | int16 | int32 | int64 | uint | uint8 | uint16 | uint32 | uint64](elems []T, sep string) string

ArrayJoin 整型拼接

elems 待拼接的数值 sep 拼接用的字符串

func CopyProperties

func CopyProperties(src, dst any) error

CopyProperties 复制结构体的属性

src: 源对象 dst: 目标对象

注意:dst必须是指针类型,且指向的结构体类型与src类型相同

Examples:

type src struct {
	Name string
	Map  map[string]int
}
type dst struct {
	Name string
	Map  map[string]int
	Age  int
}
s1 := src{Name: "test", Map: map[string]int{"a": 1}}
s2 := new(dst)
gotool.CopyProperties(s1, s2)

func CurrentDirCount

func CurrentDirCount(dir string, args ...string) (int, error)

CurrentDirCount 当前文件夹下(不迭代子文件夹)文件或文件夹的个数

dir 目录路径

Examples:

gotool.CurrentDirCount("/home/xxx") // 当前文件夹下所有文件及文件夹的个数
gotool.CurrentDirCount("/home/xxx", "file") // 当前文件夹下文件的个数
gotool.CurrentDirCount("/home/xxx", "dir") // 当前文件夹下文件夹的个数

func DirCopy

func DirCopy(src, dst string) error

DirCopy 绝对目录文件拷贝,拷贝 src 文件夹里面的内容到 dst 文件夹中

src: 源目录 dst: 目标目录

func ExecCommand

func ExecCommand(name string, arg ...string) error

ExecCommand 运行命令

name: 命令名称 arg: 命令参数

func ExecCommandWithNotify

func ExecCommandWithNotify(ch chan string, name string, arg ...string) error

ExecCommandWithNotify 带通知的运行命令

name: 命令名称 arg: 命令参数

func ExecShell

func ExecShell(shell string) error

ExecShell 运行shell命令或脚本

shell: shell 命令或脚本

func ExecShellWithNotify

func ExecShellWithNotify(ch chan string, shell string) error

ExecShellWithNotify 带通知的运行shell命令或脚本

ch: 输出通道 shell: shell 命令或脚本

func FileCopy

func FileCopy(src, dst string) error

FileCopy 文件拷贝

src: 源文件 dst: 目标文件

func FileCount

func FileCount(dir string, args ...string) (int, error)

FileCount 获取指定目录下的文件个数

dir 目录路径

Examples:

gotool.FileCount("/home/xxx") // 指定目录的文件个数
gotool.FileCount("/home/xxx", ".jpg") // 指定目录的指定后缀名的文件个数
gotool.FileCount("/home/xxx", ".jpg", ".png") // 指定目录的多个后缀名的文件个数

func FileDownload

func FileDownload(url, filePath string) error

FileDownload 文件下载

url 文件地址 filePath 文件路径

func FileMainName

func FileMainName(filePath string) string

FileMainName 获取指定路径的文件名

filePath 文件路径或文件名

Examples:

gotool.FileMainName("/opt/gotool/test.go") // test

gotool.FileMainName("test.go") // test

func FileMove

func FileMove(srcFile, dstFile string) error

FileMove 文件移动

srcFile 源文件 dstFile 目标文件

Examples:

gotool.FileMove("/opt/gotool/test.txt", "/opt/gotool/test/rename.txt")

func FileRead

func FileRead(filePath string, dst any) error

FileRead 读文件(结构体)

filePath 文件路径 dst 目标结构体

func FileSave

func FileSave(p string, data any) error

FileSave 保存文件

Examples:

gotool.FileSave("/opt/gotool/test.txt", []byte("hello world"))
gotool.FileSave("/opt/gotool/test.txt", struct{ Message string }{Message: "hello world"})

func FileSync

func FileSync(filePath string) error

FileSync 文件同步(将内存中的文件刷新到硬盘中)

filePath 文件路径

func Float64ToStr

func Float64ToStr(num float64, prec ...int) string

Float64ToStr float64转换为字符串

num: float64 prec: 精度, 及就是小数点后的位数, 默认为-1, 即不限制

func GenerateCaptcha

func GenerateCaptcha(text string) (image.Image, error)

GenerateCaptcha 验证码图片生成(目前只支持数字)

text 验证码文本

Example 1:

// image.Image to bytes
img, _ := GenerateCaptcha("5679")
var buf bytes.Buffer
err := png.Encode(&buf, img)
if err != nil {
	t.Fatal("Error encoding image:", err)
}
buf.Bytes()

func HexToInt64

func HexToInt64(str string) int64

HexToInt64 十六进制字符串转换为int64

str: 十六进制字符串

func HmacSHA256

func HmacSHA256(data []byte, key []byte) []byte

HmacSHA256 计算 SHA256

data 数据 key 密钥

func HmacSHA384

func HmacSHA384(data []byte, key []byte) []byte

HmacSHA384 计算 HmacSHA384

data 数据 key 密钥

func HmacSHA512

func HmacSHA512(data []byte, key []byte) []byte

HmacSHA512 计算 HmacSHA512

data 数据 key 密钥

func HttpDelete

func HttpDelete(url string, data any, header ...byte) ([]byte, error)

HttpDelete http delete 请求

url: 请求地址 data: 请求参数 header: 请求头

func HttpDeleteWithTimeout

func HttpDeleteWithTimeout(url string, data any, timeout time.Duration, header ...byte) ([]byte, error)

HttpDeleteWithTimeout http delete 请求带超时时长

url: 请求地址 timeout: 超时时间 data: 请求参数 header: 请求头

func HttpGet

func HttpGet(url string, header ...byte) ([]byte, error)

HttpGet http get 请求

url: 请求地址 header: 请求头

func HttpGetWithTimeout

func HttpGetWithTimeout(url string, timeout time.Duration, header ...byte) ([]byte, error)

HttpGetWithTimeout http get 请求

url: 请求地址 timeout: 超时时间 header: 请求头

func HttpPost

func HttpPost(url string, data any, header ...byte) ([]byte, error)

HttpPost http post 请求

url: 请求地址 data: 请求参数 header: 请求头

func HttpPostWithTimeout

func HttpPostWithTimeout(url string, data any, timeout time.Duration, header ...byte) ([]byte, error)

HttpPostWithTimeout http post 请求

url: 请求地址 timeout: 超时时间 data: 请求参数 header: 请求头

func HttpPut

func HttpPut(url string, data any, header ...byte) ([]byte, error)

HttpPut http put 请求

url: 请求地址 data: 请求参数 header: 请求头

func HttpPutWithTimeout

func HttpPutWithTimeout(url string, data any, timeout time.Duration, header ...byte) ([]byte, error)

HttpPutWithTimeout http put 请求

url: 请求地址 timeout: 超时时间 data: 请求参数 header: 请求头

func If

func If(condition bool, a, b any) any

If 三元运算符

condition 条件 a 条件为真时返回的值 b 条件为假时返回的值

func ImageCompression

func ImageCompression(srcFile, dstFile string, quality int) error

ImageCompression 图片压缩

srcFile 源图片路径 dstFile 目标图片路径 quality 压缩质量,范围 1-100(值越低,压缩率越高,质量越低),对于 PNG 图片,映射到 0-9 的压缩级别(0:无压缩,9:最大压缩)

func Int64ToHex

func Int64ToHex(num int64, args ...string) string

Int64ToHex int64转换为十六进制字符串

num: int64 args: 可选参数, 用于指定填充的位数以及填充的字

Examples:

gotool.Int64ToHex(15) // 返回 F
gotool.Int64ToHex(15, "08") // 返回 000F

func Int64ToStr

func Int64ToStr(num int64) string

Int64ToStr int64转换为字符串

num: int64

func Ipv4sLocal

func Ipv4sLocal() ([]string, error)

Ipv4sLocal 获取本地ipv4地址

func JWTGenerate

func JWTGenerate(claims JwtClaims, secretKey string, algorithm ...string) (string, error)

JWTGenerate 生成JWT

claims JWT声明 secretKey 密钥 algorithm 加密算法,默认为 HS256,可选值为 HS256、HS384、HS512

func MathAbs

func MathAbs[T Number](v T) T

MathAbs 绝对值

func MathMax

func MathMax[T Number](arg ...T) T

MathMax 最大值

func MathMin

func MathMin[T Number](arg ...T) T

MathMin 最小值

func Md5

func Md5(elem any, salt ...string) (string, error)

Md5 获取md5值

elem: string, []byte salt: 加盐

func Md5File

func Md5File(path string) (string, error)

Md5File 获取文件的MD5

path 文件路径

func Md5Iterations

func Md5Iterations(s any, iterations int) (string, error)

Md5Iterations 迭代多次求md5

elem: string, []byte iterations: 迭代次数

func MkParentDir

func MkParentDir(filePath string) error

MkParentDir 创建父级文件夹

filePath 文件路径

func ParseResponse

func ParseResponse[T any](respBytes []byte, err error) (T, error)

ParseResponse 解析响应

T 为返回值类型 respBytes 为响应字节数组 err httpRequest 错误

func RFC1123ToNormalTime

func RFC1123ToNormalTime(rfc1123 string) (string, error)

RFC1123ToNormalTime RFC1123 日期格式标准化

rfc1123 RFC1123日期格式,如 Mon, 02 Jan 2006 15:04:05 MST

func RFC3339ToNormalTime

func RFC3339ToNormalTime(rfc3339 string) (string, error)

RFC3339ToNormalTime RFC3339 日期格式标准化

rfc3339 RFC3339日期格式,如 2006-01-02T15:04:05Z07:00

func RandomAlpha

func RandomAlpha(length int) string

RandomAlpha 随机字母

length: 随机字母长度

func RandomAlphaNumber

func RandomAlphaNumber(length int) string

RandomAlphaNumber 随机字母数字

length: 随机字母数字长度

func RandomNumber

func RandomNumber(length int) string

RandomNumber 随机数字

length: 随机数字长度

func RandomRangeInt

func RandomRangeInt(minValue, maxValue int) int

RandomRangeInt 指定范围内的随机数 [最小值, 最大值)

minValue 最小值(包含) maxValue 最大值(不包含)

func RandomStr

func RandomStr(str string, length int) string

RandomStr 随机字符串

str: 待随机的字符串 length: 随机字符串长度

func ShouldBindJson

func ShouldBindJson(req *http.Request, data any) error

ShouldBindJson json入参绑定

r *http.Request data any 待绑定数据结构体指针

func ShouldBindQuery

func ShouldBindQuery(req *http.Request, data any) error

ShouldBindQuery query入参绑定

r *http.Request data any 待绑定数据结构体指针

func SignalSnowflake

func SignalSnowflake() int64

SignalSnowflake 单节点的雪花码

func StrToFloat32

func StrToFloat32(s string) float32

StrToFloat32 字符串转换为float32

func StrToFloat64

func StrToFloat64(s string) float64

StrToFloat64 字符串转换为float64

func StrToInt16

func StrToInt16(s string) int16

StrToInt16 字符串转换为int16

func StrToInt32

func StrToInt32(s string) int32

StrToInt32 字符串转换为int32

func StrToInt64

func StrToInt64(s string) int64

StrToInt64 字符串转换为int64

func StrToInt8

func StrToInt8(s string) int8

StrToInt8 字符串转换为int8

func StrToUint16

func StrToUint16(s string) uint16

StrToUint16 字符串转换为uint16

func StrToUint32

func StrToUint32(s string) uint32

StrToUint32 字符串转换为uint32

func StrToUint64

func StrToUint64(s string) uint64

StrToUint64 字符串转换为uint64

func StrToUint8

func StrToUint8(s string) uint8

StrToUint8 字符串转换为uint8

func SysUptime

func SysUptime() (int64, error)

SysUptime 系统启动时间(单位:毫秒)

func UUID

func UUID() (string, error)

UUID 生成uuid

func UUIDGenerate

func UUIDGenerate() string

UUIDGenerate UUID 生成

func Uint64ToStr

func Uint64ToStr(num uint64) string

Uint64ToStr uint64转换为字符串

num: uint64

func Unzip

func Unzip(src, dest string) error

Unzip 文件解压

src 文件路径 例如:/var/xxx.zip

dest 解压到的路径 例如:/var/xxx

func UnzipWithNotify

func UnzipWithNotify(src, dest string, ch chan *UnzipNotify) error

UnzipWithNotify 带通知的文件解压

src 文件路径 例如:/var/xxx.zip

dest 解压到的路径 例如:/var/xxx

ch 用于通知解压进度

func UrlBase

func UrlBase(rawURL string) string

UrlBase 获取URL路径的基础名称

rawURL 资源的网络地址

func Zip

func Zip(src, dest string) error

Zip 文件夹压缩

src 源文件夹 例如:/var/xxx

dest 压缩到的文件 例如:/var/xxx.zip

func ZipWithNotify

func ZipWithNotify(src, dest string, ch chan int) error

ZipWithNotify 带通知的文件夹压缩

src 源文件夹 例如:/var/xxx

dest 压缩到的文件 例如:/var/xxx.zip

ch 用于通知压缩进度

Types

type DownloadProgress

type DownloadProgress struct {
	Total    uint64
	FileSize uint64
}

func FileDownloadWithNotify

func FileDownloadWithNotify(ch chan DownloadProgress, url, filePath string) (*DownloadProgress, error)

FileDownloadWithNotify 带通知的文件下载

ch 通知进度 url 文件地址 filePath 文件路径

func (*DownloadProgress) Write

func (dp *DownloadProgress) Write(p []byte) (int, error)

type ImageSizeReply

type ImageSizeReply struct {
	Width  int // 图片宽
	Height int // 图片高
}

func ImageSize

func ImageSize(imagePath string) (*ImageSizeReply, error)

ImageSize 图片尺寸 说明:当图片类型不是标准库提供的,需要导入扩展库中的image golang.org/x/image

imagePath 图片路径

type JwtClaims

type JwtClaims struct {
	Expires int64          `json:"expires"` // 过期时间, 多少秒后过期, 0表示永不不过期
	Data    map[string]any `json:"data"`    // 数据
}

func JWTParse

func JWTParse(jwt string, secretKey string, algorithm ...string) (*JwtClaims, error)

JWTParse 解析JWT

jwt JWT字符串 secretKey 密钥 algorithm 加密算法,默认为 HS256,可选值为 HS256、HS384、HS512

type Mail

type Mail struct {
	Username string // 用户名
	Password string // 密码
	Addr     string // smtp地址, 例如 mail.example.com:smtp
	From     string // 发送者
}

func (Mail) SendMail

func (mail Mail) SendMail(receiveUsers []string, subject, content string) error

SendMail 发送邮件

receiveUsers: 接收者 subject: 主题 content: 正文

type Number

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

type Process

type Process struct {
	Pid  string `json:"pid"`  // 进程ID号
	PPid string `json:"ppid"` // 进程父级ID号
	Cmd  string `json:"cmd"`  // 执行的命令
}

func PsByName

func PsByName(name string) ([]Process, error)

PsByName 根据程序名查询进程列表

name: 程序名

type Snowflake

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

Snowflake 结构体

func NewSnowflake

func NewSnowflake(epoch int64, nodeID uint8) *Snowflake

NewSnowflake 创建 Snowflake 实例

epoch: 起始时间戳 nodeID: 节点ID

func (*Snowflake) GenerateSnowflake

func (s *Snowflake) GenerateSnowflake() int64

GenerateSnowflake 生成新的雪花码

type Stream

type Stream[T any] struct {
	// contains filtered or unexported fields
}

func NewStream

func NewStream[T any](data []T) *Stream[T]

NewStream 初始化 Stream

func StreamMap

func StreamMap[T, R any](s *Stream[T], f func(T) R) *Stream[R]

StreamMap 数据处理与转换

Examples:

s := NewStream([]int{1, 2, 3, 4, 5})

StreamMap(s, func(v int) string { return fmt.Sprintf("data: %d", v) })

func (*Stream[T]) Filter

func (s *Stream[T]) Filter(f func(T) bool) *Stream[T]

Filter 数据过滤

Examples:

s := NewStream([]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})

s.Filter(func(v int) bool { return v%2 == 0 }) // []int{2, 4, 6, 8, 10}

func (*Stream[T]) Map

func (s *Stream[T]) Map(fn func(item T) T) *Stream[T]

Map 数据处理

Examples:

s := NewStream([]int{1, 2, 3, 4, 5})

s.Map(func(v int) int { return v * 2 })

func (*Stream[T]) Max

func (s *Stream[T]) Max(fn func(a, b T) bool) T

Max 数据最大值, a > b

Examples:

s := NewStream([]int{1, 2, 3, 4, 5})

s.Max(func(a, b int) bool { return a > b }) // 5

func (*Stream[T]) ToSlice

func (s *Stream[T]) ToSlice() []T

ToSlice 转换为切片

type TemperatureStat

type TemperatureStat struct {
	SensorType  string  `json:"sensorType"`  // 传感器
	Temperature float64 `json:"temperature"` // 温度
}

func CPUTemperatures

func CPUTemperatures() []*TemperatureStat

CPUTemperatures 获取CPU温度

type UnzipNotify

type UnzipNotify struct {
	Progress int    `json:"progress"` // 解压进度
	FPath    string `json:"f_path"`   // 解压文件的路径
}

Jump to

Keyboard shortcuts

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