common

package
v1.3.0 Latest Latest
Warning

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

Go to latest
Published: Mar 13, 2025 License: MIT Imports: 39 Imported by: 0

README

Common工具包

本目录包含各种通用工具函数,包括文件处理、加解密、HTTP请求和并发控制等实用功能。

1. 文件工具 (file.go)

file.go 提供了丰富的文件和目录操作函数,简化常见的文件处理任务。

文件检测函数
// 检查路径是否存在
exists, err := PathExists("/path/to/file")

// 检查路径是否是目录
isDir, err := IsDir("/path/to/dir")

// 检查路径是否是文件
isFile, err := IsFile("/path/to/file")
文件创建和删除
// 创建目录(支持递归创建)
err := CreateDir("/path/to/new/dir")

// 删除文件
err := RemoveFile("/path/to/file")

// 删除目录及其内容
err := RemoveDir("/path/to/dir")

// 创建空文件或更新已有文件的访问和修改时间
err := TouchFile("/path/to/file")
文件复制和移动
// 复制文件
err := CopyFile("/path/source", "/path/destination")

// 移动/重命名文件
err := MoveFile("/path/source", "/path/destination")
文件内容读写
// 读取文件内容为字符串
content, err := ReadFile("/path/to/file")

// 将字符串写入文件(覆盖)
err := WriteFile("/path/to/file", "文件内容")

// 追加内容到文件
err := AppendToFile("/path/to/file", "追加的内容")

// 读取文件的所有行
lines, err := ReadLines("/path/to/file")
文件遍历
// 列出目录中的所有文件(递归)
files, err := ListFiles("/path/to/dir")

// 列出目录中的所有子目录(递归)
dirs, err := ListDirs("/path/to/dir")

// 在指定目录中查找特定扩展名的文件
jpgFiles, err := FindFilesByExt("/path/to/dir", ".jpg")
文件信息获取
// 获取文件大小(字节)
size, err := GetFileSize("/path/to/file")

// 格式化文件大小(转换为KB/MB/GB等)
formattedSize := FormatFileSize(sizeInBytes)

// 获取文件扩展名
ext := GetFileExt("/path/to/file.txt") // 返回 ".txt"

// 获取文件基本名称(不包含扩展名)
name := GetBaseName("/path/to/file.txt") // 返回 "file"

// 计算文件的MD5哈希值
md5hash, err := GetFileMD5("/path/to/file")

// 获取文件的最后修改时间(Unix时间戳)
modTime, err := FileModTime("/path/to/file")

// 检查文件是否比指定时间戳更早
isOlder, err := IsFileOlderThan("/path/to/file", timestamp)

// 递归计算目录大小
dirSize, err := DirSize("/path/to/dir")

2. 加解密工具 (crypto.go)

crypto.go 提供了常用的加密、解密和编码功能,简化数据安全处理。

Base64 编解码
// 标准Base64编码
encodedStr := Base64Encode([]byte("Hello World"))

// 标准Base64解码
decodedBytes, err := Base64Decode(encodedStr)

// URL安全的Base64编码
urlSafeStr := Base64UrlEncode([]byte("Hello World"))

// URL安全的Base64解码
decodedBytes, err := Base64UrlDecode(urlSafeStr)
URL 编解码
// URL编码
encoded := UrlEncode("Hello World & More")

// URL解码
decoded, err := UrlDecode(encoded)
哈希计算
// 计算MD5哈希
md5hash := MD5Hash("Hello World")

// 计算SHA1哈希
sha1hash := SHA1Hash("Hello World")

// 计算SHA256哈希
sha256hash := SHA256Hash("Hello World")
密码处理
// 对密码进行哈希处理
hashedPassword, err := HashPassword("my-secure-password")

// 验证密码与哈希值是否匹配
isMatch := CheckPasswordHash("my-secure-password", hashedPassword)
AES 加解密
// 生成AES密钥 (128, 192 或 256 位)
key, err := GenerateAESKey(256)

// AES加密
cipherText, err := AESEncrypt([]byte("明文数据"), key)

// AES解密
plainText, err := AESDecrypt(cipherText, key)

// 字符串加密(AES加密+Base64编码)
encryptedStr, err := EncryptString("明文字符串", key)

// 字符串解密
decryptedStr, err := DecryptString(encryptedStr, key)
RSA 加解密
// 生成RSA密钥对
publicKey, privateKey, err := GenerateRSAKeyPair(2048)

// RSA公钥加密
cipherText, err := RSAEncrypt([]byte("明文数据"), publicKey)

// RSA私钥解密
plainText, err := RSADecrypt(cipherText, privateKey)
随机数生成
// 生成随机字节
randomBytes, err := GenerateRandomBytes(16)

// 生成随机字符串
randomString, err := GenerateRandomString(12)

// 生成安全的随机令牌
token, err := GenerateSecureToken(32)

3. HTTP请求工具 (http.go)

http.go 提供了简洁易用的HTTP客户端,支持各种HTTP请求方式和高级功能。

基本用法
// 创建HTTP客户端
client := NewHTTPClient()

// 设置基础URL
client.SetBaseURL("https://api.example.com")

// 设置超时
client.SetTimeout(30 * time.Second)

// 设置请求头
client.SetHeader("User-Agent", "MyApp/1.0")

// 设置认证
client.SetBasicAuth("username", "password")
// 或
client.SetBearerAuth("your-token")

// 设置重试
client.SetRetry(3, 1 * time.Second)
发送请求
// GET请求
resp, err := client.Get("/users", map[string]string{"page": "1"})

// POST请求 (JSON)
resp, err := client.Post("/users", map[string]interface{}{
    "name": "张三",
    "age": 30,
})

// PUT请求
resp, err := client.Put("/users/1", userData)

// DELETE请求
resp, err := client.Delete("/users/1")

// 表单POST请求
resp, err := client.PostForm("/login", map[string]string{
    "username": "user",
    "password": "pass",
})

// 上传文件
resp, err := client.UploadFile(
    "/upload", 
    "file", 
    "./document.pdf",
    map[string]string{"description": "My Document"}
)
JSON处理
// GET请求并解析JSON响应
var users []User
err := client.GetJSON("/users", nil, &users)

// POST请求并解析JSON响应
var user User
err := client.PostJSON("/users", userData, &user)
文件下载
// 下载文件
err := client.Download("https://example.com/file.zip", "./downloads/file.zip")
简单请求函数
// 简单GET请求
data, err := SimpleGet("https://example.com/api/data")

// 简单POST请求 (JSON)
data, err := SimplePostJSON("https://example.com/api/users", userData)

4. 并发线程工具 (concurrency.go)

concurrency.go 提供了并发编程相关的工具,简化多线程任务处理。

线程安全的数据结构
// 线程安全的计数器
counter := SafeCounter{}
counter.Increment()
value := counter.Get()
counter.Decrement()

// 线程安全的映射
safeMap := NewSafeMap()
safeMap.Set("key", "value")
value := safeMap.Get("key")
safeMap.Delete("key")
线程池
// 创建线程池 (工作线程数=5, 队列大小=100)
pool := NewThreadPool(5, 100)

// 提交任务
pool.Submit(func() (interface{}, error) {
    // 任务逻辑
    return nil, nil
})

// 等待所有任务完成
pool.Wait()

// 停止线程池
pool.Stop()
并行执行器
// 创建并行执行器
parallelizer := NewParallelizer(10, 30 * time.Second)

// 准备任务
tasks := []Task{
    func() (interface{}, error) { return "任务1结果", nil },
    func() (interface{}, error) { return "任务2结果", nil },
}

// 并行执行任务
results := parallelizer.Run(tasks)

// 处理结果
for _, result := range results {
    if result.Error != nil {
        fmt.Println("错误:", result.Error)
    } else {
        fmt.Println("结果:", result.Value)
    }
}
简便的并发执行函数
// 使用超时并行执行任务
results := RunTasksWithTimeout(10 * time.Second, task1, task2, task3)

// 限制并发数量执行任务
results := RunTasksConcurrently(5, task1, task2, task3, task4, task5)
信号量
// 创建一个大小为3的信号量
sem := NewSemaphore(3)

// 获取信号量
sem.Acquire()

// 带超时获取信号量
success := sem.AcquireWithTimeout(5 * time.Second)

// 尝试获取信号量(不阻塞)
if sem.TryAcquire() {
    // 成功获取信号量
}

// 释放信号量
sem.Release()
速率限制器
// 创建每秒10个请求的速率限制器
limiter := NewRateLimiter(10)

// 等待获取令牌
limiter.Wait()

// 带速率限制执行函数
RunWithRateLimit(10, func() {
    // 限制频率的操作
})
批量处理
// 批量处理数据
items := []string{"item1", "item2", "item3", "item4", "item5"}
err := BatchProcess(items, 2, 3, func(batch []string) error {
    // 处理一批数据
    return nil
})

文件工具使用示例

package main

import (
	"fmt"
	"github.com/SmartRick/my-go-sdk/common"
	"time"
)

func main() {
	// 创建目录
	err := common.CreateDir("./test_dir")
	if err != nil {
		fmt.Println("创建目录失败:", err)
		return
	}
	
	// 写入文件
	err = common.WriteFile("./test_dir/test.txt", "Hello, World!")
	if err != nil {
		fmt.Println("写入文件失败:", err)
		return
	}
	
	// 检查文件是否存在
	exists, _ := common.PathExists("./test_dir/test.txt")
	fmt.Println("文件存在:", exists)
	
	// 获取文件信息
	size, _ := common.GetFileSize("./test_dir/test.txt")
	fmt.Println("文件大小:", common.FormatFileSize(size))
	
	// 计算MD5
	md5, _ := common.GetFileMD5("./test_dir/test.txt")
	fmt.Println("文件MD5:", md5)
	
	// 复制文件
	err = common.CopyFile("./test_dir/test.txt", "./test_dir/test_copy.txt")
	if err != nil {
		fmt.Println("复制文件失败:", err)
	}
	
	// 列出目录文件
	files, _ := common.ListFiles("./test_dir")
	fmt.Println("目录中的文件:")
	for _, file := range files {
		fmt.Println("- ", file)
	}
	
	// 追加内容
	common.AppendToFile("./test_dir/test.txt", "\n这是追加的内容")
	
	// 读取文件内容
	content, _ := common.ReadFile("./test_dir/test.txt")
	fmt.Println("更新后的文件内容:", content)
	
	// 清理测试文件
	time.Sleep(2 * time.Second) // 等待一下,以便看到测试结果
	common.RemoveDir("./test_dir")
	fmt.Println("测试完成,清理测试文件")
}

未来计划

未来将添加更多通用工具功能,例如:

  • 日志工具:提供灵活的日志记录功能
  • 配置管理:支持多种配置格式的读取和管理
  • 时间工具:时间格式化、时区转换、计时器等
  • 字符串处理:字符串验证、转换、格式化等
  • 数据库工具:数据库连接池管理、简化的CRUD操作

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AESDecrypt

func AESDecrypt(cipherText []byte, key []byte) ([]byte, error)

AESDecrypt 使用AES-GCM算法解密数据

func AESEncrypt

func AESEncrypt(plainText []byte, key []byte) ([]byte, error)

AESEncrypt 使用AES-GCM算法加密数据

func AppendToFile

func AppendToFile(filePath, content string) error

AppendToFile 追加内容到文件

func Base64Decode

func Base64Decode(encoded string) ([]byte, error)

Base64Decode 将base64字符串解码为字节数组

func Base64Encode

func Base64Encode(data []byte) string

Base64Encode 将字节数组编码为base64字符串

func Base64UrlDecode

func Base64UrlDecode(encoded string) ([]byte, error)

Base64UrlDecode 将URL安全的base64字符串解码为字节数组

func Base64UrlEncode

func Base64UrlEncode(data []byte) string

Base64UrlEncode 将字节数组编码为URL安全的base64字符串

func BatchProcess

func BatchProcess[T any](items []T, batchSize int, maxGoroutines int, processBatch func(batch []T) error) error

BatchProcess 批量处理数据,将数据分成多个批次并行处理

func BytesToImage added in v1.3.0

func BytesToImage(data []byte) (image.Image, error)

BytesToImage 将bytes转换成image

func Capitalize

func Capitalize(s string) string

Capitalize 首字母大写

func CenterAlign

func CenterAlign(s string, width int, padChar rune) string

CenterAlign 使字符串居中对齐

func CheckPasswordHash

func CheckPasswordHash(password, hash string) bool

CheckPasswordHash 验证密码与哈希值是否匹配

func ContainsAll

func ContainsAll(s string, subs ...string) bool

ContainsAll 判断字符串是否包含所有给定的子字符串

func ContainsAny

func ContainsAny(s string, subs ...string) bool

ContainsAny 判断字符串是否包含任意给定的子字符串

func CopyFile

func CopyFile(src, dst string) error

CopyFile 复制文件

func CountLines

func CountLines(s string) int

CountLines 统计文本的行数

func CountSubstring

func CountSubstring(s, sub string) int

CountSubstring 计算子字符串出现次数

func CountWords

func CountWords(s string) int

CountWords 统计文本中的单词数量

func CreateDir

func CreateDir(dirPath string) error

CreateDir 创建目录,支持递归创建

func DecryptString

func DecryptString(encryptedText string, key []byte) (string, error)

DecryptString 解密Base64编码的AES加密字符串

func DiffWords

func DiffWords(s1, s2 string) ([]string, []string)

DiffWords 比较两个字符串的差异(返回两个字符串中不同的单词)

func DirSize

func DirSize(dirPath string) (int64, error)

DirSize 递归计算目录大小

func EncryptString

func EncryptString(plainText string, key []byte) (string, error)

EncryptString 使用AES加密字符串并返回Base64编码的结果

func EndsWith

func EndsWith(s, suffix string, ignoreCase bool) bool

EndsWith 判断字符串是否以指定后缀结束(忽略大小写)

func EscapeHTML

func EscapeHTML(s string) string

EscapeHTML 转义HTML特殊字符

func ExtractAllBetween

func ExtractAllBetween(s, start, end string) []string

ExtractAllBetween 提取两个标记之间的所有字符串

func ExtractBetween

func ExtractBetween(s, start, end string) string

ExtractBetween 提取两个标记之间的字符串

func FileModTime

func FileModTime(filePath string) (int64, error)

FileModTime 获取文件的最后修改时间

func FindFilesByExt

func FindFilesByExt(dirPath string, ext string) ([]string, error)

FindFilesByExt 在指定目录中查找特定扩展名的文件

func FindLongestWord

func FindLongestWord(s string) string

FindLongestWord 查找文本中最长的单词

func FirstN

func FirstN(s string, n int) string

FirstN 返回字符串的前N个字符

func FormatFileSize

func FormatFileSize(sizeInBytes int64) string

FormatFileSize 格式化文件大小(转换为KB/MB/GB等)

func FormatInt

func FormatInt(n int) string

FormatInt 格式化整数为千分位形式

func FormatTemplate

func FormatTemplate(template string, data map[string]interface{}) string

FormatTemplate 简单的字符串模板替换

func FromJSON

func FromJSON(jsonStr string, obj interface{}) error

FromJSON 从JSON字符串解析对象

func GenerateAESKey

func GenerateAESKey(bits int) ([]byte, error)

GenerateAESKey 生成指定位数的AES密钥

func GenerateRSAKeyPair

func GenerateRSAKeyPair(bits int) (string, string, error)

GenerateRSAKeyPair 生成RSA公钥和私钥对

func GenerateRandomBytes

func GenerateRandomBytes(n int) ([]byte, error)

GenerateRandomBytes 生成指定数量的随机字节

func GenerateRandomString

func GenerateRandomString(length int, charset string) string

GenerateRandomString 生成随机字符串

func GenerateSecureToken

func GenerateSecureToken(length int) (string, error)

GenerateSecureToken 生成安全的随机令牌

func GetBaseName

func GetBaseName(filePath string) string

GetBaseName 获取文件基本名称(不包含扩展名)

func GetFileExt

func GetFileExt(filePath string) string

GetFileExt 获取文件扩展名

func GetFileMD5

func GetFileMD5(filePath string) (string, error)

GetFileMD5 计算文件的MD5哈希值

func GetFileSize

func GetFileSize(filePath string) (int64, error)

GetFileSize 获取文件大小(字节)

func HashPassword

func HashPassword(password string) (string, error)

HashPassword 使用bcrypt对密码进行哈希处理

func ImageToBytes added in v1.3.0

func ImageToBytes(img image.Image) ([]byte, error)

ImageToBytes 将image转换成bytes

func InsertAt

func InsertAt(s string, index int, insert string) string

InsertAt 在指定位置插入字符串

func IsAlpha

func IsAlpha(s string) bool

IsAlpha 判断字符串是否只包含字母

func IsAlphaNumeric

func IsAlphaNumeric(s string) bool

IsAlphaNumeric 判断字符串是否只包含字母和数字

func IsBlank

func IsBlank(s string) bool

IsBlank 判断字符串是否为空白(空字符串或只包含空白字符)

func IsChinaPhoneNumber

func IsChinaPhoneNumber(s string) bool

IsChinaPhoneNumber 验证是否为中国手机号

func IsClientError

func IsClientError(statusCode int) bool

IsClientError 检查HTTP状态码是否表示客户端错误

func IsDir

func IsDir(path string) (bool, error)

IsDir 检查路径是否是目录

func IsEmail

func IsEmail(s string) bool

IsEmail 验证是否为邮箱地址

func IsEmpty

func IsEmpty(s string) bool

IsEmpty 判断字符串是否为空

func IsFile

func IsFile(path string) (bool, error)

IsFile 检查路径是否是文件

func IsFileOlderThan

func IsFileOlderThan(filePath string, timestamp int64) (bool, error)

IsFileOlderThan 检查文件是否比指定时间戳更早

func IsIDCard

func IsIDCard(s string) bool

IsIDCard 验证是否为中国身份证号(18位)

func IsIPv4

func IsIPv4(s string) bool

IsIPv4 验证是否为IPv4地址

func IsNumeric

func IsNumeric(s string) bool

IsNumeric 判断字符串是否只包含数字

func IsRedirect

func IsRedirect(statusCode int) bool

IsRedirect 检查HTTP状态码是否表示重定向

func IsServerError

func IsServerError(statusCode int) bool

IsServerError 检查HTTP状态码是否表示服务器错误

func IsSuccess

func IsSuccess(statusCode int) bool

IsSuccess 检查HTTP状态码是否表示成功

func IsURL

func IsURL(s string) bool

IsURL 验证是否为URL

func JoinStrings

func JoinStrings(elements []string, separator string) string

JoinStrings 连接字符串数组,带分隔符

func LastN

func LastN(s string, n int) string

LastN 返回字符串的后N个字符

func ListDirs

func ListDirs(dirPath string) ([]string, error)

ListDirs 列出目录中的所有子目录

func ListFiles

func ListFiles(dirPath string) ([]string, error)

ListFiles 列出目录中的所有文件

func MD5Hash

func MD5Hash(data string) string

MD5Hash 计算字符串的MD5哈希值

func MaskMiddleChars

func MaskMiddleChars(s string, keepStart, keepEnd int, maskChar rune) string

MaskMiddleChars 对字符串中间部分进行掩码处理,保留前n个和后m个字符

func MaskString

func MaskString(s string, start, end int, maskChar rune) string

MaskString 对字符串进行掩码处理,例如银行卡号、手机号等

func MatchPattern

func MatchPattern(s, pattern string) (bool, error)

MatchPattern 判断字符串是否匹配正则表达式

func MoveFile

func MoveFile(src, dst string) error

MoveFile 移动/重命名文件

func PadLeft

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

PadLeft 左填充

func PadRight

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

PadRight 右填充

func ParseBool

func ParseBool(s string, defaultValue bool) bool

ParseBool 解析布尔值(包含异常处理)

func ParseFloat

func ParseFloat(s string, defaultValue float64) float64

ParseFloat 解析浮点数(包含异常处理)

func ParseInt

func ParseInt(s string, defaultValue int) int

ParseInt 解析整数(包含异常处理)

func PathExists

func PathExists(path string) (bool, error)

PathExists 检查路径是否存在

func PrettyJSON

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

PrettyJSON 将对象转换为格式化的JSON字符串

func RSADecrypt

func RSADecrypt(cipherText []byte, privateKeyPEM string) ([]byte, error)

RSADecrypt 使用RSA私钥解密数据

func RSAEncrypt

func RSAEncrypt(plainText []byte, publicKeyPEM string) ([]byte, error)

RSAEncrypt 使用RSA公钥加密数据

func RandomSubstring

func RandomSubstring(s string, length int) string

RandomSubstring 随机返回字符串的一个子串

func ReadFile

func ReadFile(filePath string) (string, error)

ReadFile 读取文件内容为字符串

func ReadLines

func ReadLines(filePath string) ([]string, error)

ReadLines 读取文件的所有行

func RemoveAccents

func RemoveAccents(s string) string

RemoveAccents 移除字符串中的变音符号

func RemoveAt

func RemoveAt(s string, index, count int) string

RemoveAt 删除指定位置的n个字符

func RemoveDir

func RemoveDir(dirPath string) error

RemoveDir 删除目录及其内容

func RemoveFile

func RemoveFile(filePath string) error

RemoveFile 删除文件

func ReverseString

func ReverseString(s string) string

ReverseString 字符串反转

func RunWithRateLimit

func RunWithRateLimit(maxRequestsPerSecond int, fn func())

RunWithRateLimit 使用速率限制执行函数

func SHA1Hash

func SHA1Hash(data string) string

SHA1Hash 计算字符串的SHA1哈希值

func SHA256Hash

func SHA256Hash(data string) string

SHA256Hash 计算字符串的SHA256哈希值

func SimpleGet

func SimpleGet(url string) ([]byte, error)

SimpleGet 简单的GET请求

func SimplePost

func SimplePost(url string, contentType string, body io.Reader) ([]byte, error)

SimplePost 简单的POST请求

func SimplePostJSON

func SimplePostJSON(url string, data interface{}) ([]byte, error)

SimplePostJSON 简单的POST JSON请求

func SlugifyString

func SlugifyString(s string) string

SlugifyString 将字符串转换为URL友好的格式

func SplitAndTrim

func SplitAndTrim(s, sep string) []string

SplitAndTrim 分割字符串并去除空白

func SplitByLength

func SplitByLength(s string, length int) []string

SplitByLength 按照指定长度分割字符串

func StartsWith

func StartsWith(s, prefix string, ignoreCase bool) bool

StartsWith 判断字符串是否以指定前缀开始(忽略大小写)

func StringExamples

func StringExamples()

StringExamples 展示字符串处理工具的使用示例

func SwapCase

func SwapCase(s string) string

SwapCase 大小写反转

func ToJSON

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

ToJSON 将对象转换为JSON字符串

func ToKebabCase

func ToKebabCase(s string) string

ToKebabCase 转换为短横线命名(例如 hello-world)

func ToLowerCamel

func ToLowerCamel(s string) string

ToLowerCamel 转换为小驼峰命名(例如 helloWorld)

func ToSnakeCase

func ToSnakeCase(s string) string

ToSnakeCase 转换为蛇形命名(例如 hello_world)

func ToUpperCamel

func ToUpperCamel(s string) string

ToUpperCamel 转换为大驼峰命名(例如 HelloWorld)

func TouchFile

func TouchFile(filePath string) error

TouchFile 创建空文件或更新现有文件的访问和修改时间

func TruncateString

func TruncateString(s string, maxLength int) string

TruncateString 截断字符串并添加省略号

func Uncapitalize

func Uncapitalize(s string) string

Uncapitalize 首字母小写

func UnescapeHTML

func UnescapeHTML(s string) string

UnescapeHTML 反转义HTML特殊字符

func UrlDecode

func UrlDecode(encoded string) (string, error)

UrlDecode 对URL编码的字符串进行解码

func UrlEncode

func UrlEncode(data string) string

UrlEncode 对字符串进行URL编码

func WordCount

func WordCount(s string) int

WordCount 统计单词数量

func WrapText

func WrapText(s string, width int) string

WrapText 根据指定宽度进行文本换行

func WriteFile

func WriteFile(filePath, content string) error

WriteFile 将字符串写入文件

Types

type HTTPClient

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

HTTPClient 封装HTTP客户端

func NewHTTPClient

func NewHTTPClient() *HTTPClient

NewHTTPClient 创建一个新的HTTP客户端

func (*HTTPClient) Delete

func (c *HTTPClient) Delete(path string) (*http.Response, error)

Delete 发送DELETE请求

func (*HTTPClient) DeleteJSON

func (c *HTTPClient) DeleteJSON(path string, v interface{}) error

DeleteJSON 发送DELETE请求并解析JSON响应

func (*HTTPClient) Download

func (c *HTTPClient) Download(url, savePath string) error

Download 下载文件

func (*HTTPClient) Get

func (c *HTTPClient) Get(path string, params map[string]string) (*http.Response, error)

Get 发送GET请求

func (*HTTPClient) GetJSON

func (c *HTTPClient) GetJSON(path string, params map[string]string, v interface{}) error

GetJSON 发送GET请求并解析JSON响应

func (*HTTPClient) Post

func (c *HTTPClient) Post(path string, body interface{}) (*http.Response, error)

Post 发送POST请求

func (*HTTPClient) PostForm

func (c *HTTPClient) PostForm(path string, formData map[string]string) (*http.Response, error)

PostForm 发送表单POST请求

func (*HTTPClient) PostJSON

func (c *HTTPClient) PostJSON(path string, body, v interface{}) error

PostJSON 发送POST请求并解析JSON响应

func (*HTTPClient) Put

func (c *HTTPClient) Put(path string, body interface{}) (*http.Response, error)

Put 发送PUT请求

func (*HTTPClient) PutJSON

func (c *HTTPClient) PutJSON(path string, body, v interface{}) error

PutJSON 发送PUT请求并解析JSON响应

func (*HTTPClient) SetBaseURL

func (c *HTTPClient) SetBaseURL(baseURL string) *HTTPClient

SetBaseURL 设置基础URL

func (*HTTPClient) SetBasicAuth

func (c *HTTPClient) SetBasicAuth(username, password string) *HTTPClient

SetBasicAuth 设置基本认证

func (*HTTPClient) SetBearerAuth

func (c *HTTPClient) SetBearerAuth(token string) *HTTPClient

SetBearerAuth 设置Bearer令牌认证

func (*HTTPClient) SetHeader

func (c *HTTPClient) SetHeader(key, value string) *HTTPClient

SetHeader 设置请求头

func (*HTTPClient) SetHeaders

func (c *HTTPClient) SetHeaders(headers map[string]string) *HTTPClient

SetHeaders 批量设置请求头

func (*HTTPClient) SetRetry

func (c *HTTPClient) SetRetry(maxRetry int, retryWait time.Duration) *HTTPClient

SetRetry 设置重试参数

func (*HTTPClient) SetTimeout

func (c *HTTPClient) SetTimeout(timeout time.Duration) *HTTPClient

SetTimeout 设置请求超时时间

func (*HTTPClient) UploadFile

func (c *HTTPClient) UploadFile(path string, fieldName, filePath string, params map[string]string) (*http.Response, error)

UploadFile 上传文件

type Parallelizer

type Parallelizer struct {
	MaxGoroutines int
	Timeout       time.Duration
}

Parallelizer 并行执行多个任务

func NewParallelizer

func NewParallelizer(maxGoroutines int, timeout time.Duration) *Parallelizer

NewParallelizer 创建一个新的并行执行器

func (*Parallelizer) Run

func (p *Parallelizer) Run(tasks []Task) []TaskResult

Run 并行执行任务列表

func (*Parallelizer) RunWithContext

func (p *Parallelizer) RunWithContext(ctx context.Context, tasks []Task) []TaskResult

RunWithContext 带有上下文的并行执行任务列表

type RateLimiter

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

RateLimiter 速率限制器

func NewRateLimiter

func NewRateLimiter(maxRequestsPerSecond int) *RateLimiter

NewRateLimiter 创建一个新的速率限制器

func (*RateLimiter) Close

func (r *RateLimiter) Close()

Close 关闭速率限制器

func (*RateLimiter) TryWait

func (r *RateLimiter) TryWait() bool

TryWait 尝试获取令牌,如果不可用则立即返回false

func (*RateLimiter) Wait

func (r *RateLimiter) Wait()

Wait 等待获取令牌

type SafeCounter

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

SafeCounter 线程安全的计数器

func (*SafeCounter) Decrement

func (c *SafeCounter) Decrement() int64

Decrement 减少计数器的值

func (*SafeCounter) Get

func (c *SafeCounter) Get() int64

Get 获取计数器的当前值

func (*SafeCounter) Increment

func (c *SafeCounter) Increment() int64

Increment 增加计数器的值

func (*SafeCounter) Set

func (c *SafeCounter) Set(value int64)

Set 设置计数器的值

type SafeMap

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

SafeMap 线程安全的映射

func NewSafeMap

func NewSafeMap() *SafeMap

NewSafeMap 创建一个新的线程安全映射

func (*SafeMap) Clear

func (m *SafeMap) Clear()

Clear 清空映射

func (*SafeMap) Delete

func (m *SafeMap) Delete(key string)

Delete 删除键

func (*SafeMap) Get

func (m *SafeMap) Get(key string) interface{}

Get 获取值,如果键不存在则返回nil

func (*SafeMap) GetWithDefault

func (m *SafeMap) GetWithDefault(key string, defaultValue interface{}) interface{}

GetWithDefault 获取值,如果键不存在则返回默认值

func (*SafeMap) Has

func (m *SafeMap) Has(key string) bool

Has 检查键是否存在

func (*SafeMap) Keys

func (m *SafeMap) Keys() []string

Keys 返回所有键的列表

func (*SafeMap) Len

func (m *SafeMap) Len() int

Len 返回映射的大小

func (*SafeMap) Set

func (m *SafeMap) Set(key string, value interface{})

Set 设置键值对

func (*SafeMap) Values

func (m *SafeMap) Values() []interface{}

Values 返回所有值的列表

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()

Acquire 获取信号量

func (*Semaphore) AcquireWithTimeout

func (s *Semaphore) AcquireWithTimeout(timeout time.Duration) bool

AcquireWithTimeout 在指定的超时时间内获取信号量

func (*Semaphore) Available

func (s *Semaphore) Available() int

Available 返回当前可用的信号量数量

func (*Semaphore) Release

func (s *Semaphore) Release()

Release 释放信号量

func (*Semaphore) TryAcquire

func (s *Semaphore) TryAcquire() bool

TryAcquire 尝试获取信号量,如果不可用则立即返回false

type Task

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

Task 表示要执行的任务

type TaskResult

type TaskResult struct {
	Value interface{}
	Error error
	Index int
}

TaskResult 表示任务的执行结果

func RunTasksConcurrently

func RunTasksConcurrently(maxGoroutines int, tasks ...Task) []TaskResult

RunTasksConcurrently 并发执行多个任务

func RunTasksWithTimeout

func RunTasksWithTimeout(timeout time.Duration, tasks ...Task) []TaskResult

RunTasksWithTimeout 在指定的超时时间内并行执行多个任务

type TaskWithContext

type TaskWithContext func(ctx context.Context) (interface{}, error)

TaskWithContext 表示带有上下文的任务

type ThreadPool

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

ThreadPool 表示一个线程池

func NewThreadPool

func NewThreadPool(workers int, queueSize int) *ThreadPool

NewThreadPool 创建一个新的线程池

func (*ThreadPool) Stop

func (p *ThreadPool) Stop()

Stop 停止线程池

func (*ThreadPool) Submit

func (p *ThreadPool) Submit(task Task) error

Submit 提交一个任务到线程池

func (*ThreadPool) Wait

func (p *ThreadPool) Wait()

Wait 等待所有任务完成

Jump to

Keyboard shortcuts

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