utils

package
v1.4.0 Latest Latest
Warning

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

Go to latest
Published: Jul 13, 2026 License: MIT Imports: 30 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var DefaultHTTPClientConfig = HTTPClientConfig{
	Timeout:             30 * time.Second,
	MaxIdleConns:        100,
	IdleConnTimeout:     90 * time.Second,
	MaxConnsPerHost:     10,
	MaxIdleConnsPerHost: 10,
	SkipTLSVerify:       false,
	MaxResponseBodySize: 32 * 1024 * 1024,
}

DefaultHTTPClientConfig 是包级默认 HTTP 客户端配置。

View Source
var ErrRandInvalidLength = errors.New("invalid random length")

ErrRandInvalidLength 长度过大(超过 1<<20,保护熵池)。n<=0 时返回空串而非此错误。

View Source
var ErrSSRFBlocked = errors.New("ssrf guard: 目标 IP 属于被拦截的网络范围")

ErrSSRFBlocked 表示 SSRF 防护拦截了目标 IP。

Functions

func AppendFile

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

AppendFile 追加内容到文件

func Base64Decode

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

Base64Decode Base64 解码

func Base64Encode

func Base64Encode(data []byte) string

Base64Encode Base64 编码

func Base64URLDecode

func Base64URLDecode(s string) ([]byte, error)

Base64URLDecode URL 安全的 Base64 解码

func Base64URLEncode

func Base64URLEncode(data []byte) string

Base64URLEncode URL 安全的 Base64 编码

func CalcOffset

func CalcOffset(page, pageSize int) int

CalcOffset 计算分页偏移量 (page-1)*pageSize。page<=0 时按 1 处理,pageSize<=0 时按 20 处理。

func CalcPageCount

func CalcPageCount(total, pageSize int64) int64

CalcPageCount 计算总页数(向上取整)。total<=0 或 pageSize<=0 时返回 0。

func CopyFile

func CopyFile(dst, src string) error

CopyFile 将 src 复制到 dst(覆盖),自动创建目标目录。src 不存在时返回其 Open 错误。

func DefaultIfBlank

func DefaultIfBlank(s, def string) string

DefaultIfBlank 如果字符串为空或空白,返回默认值

func DirExists

func DirExists(path string) bool

DirExists 检查目录是否存在

func EndOfDay

func EndOfDay(t time.Time) time.Time

EndOfDay 返回指定时间当天的结束时间 (23:59:59.999999999)

func EndOfMonth

func EndOfMonth(t time.Time) time.Time

EndOfMonth 返回指定时间当月最后一天 23:59:59.999999999(保留原时区)。

func EnsureDir

func EnsureDir(path string) error

EnsureDir 确保目录存在,不存在则创建

func EqualsIgnoreCase

func EqualsIgnoreCase(a, b string) bool

EqualsIgnoreCase 不区分大小写比较字符串。

L-C 修复:改用 strings.EqualFold(标准库 Unicode 大小写折叠)。原实现仅做 ASCII 字节级折叠('A'-'Z' → +32),对非 ASCII 字符(如 "É" vs "é")误判为不等。 EqualFold 同时更快(无逐字节循环开销)。

func FileExists

func FileExists(path string) bool

FileExists 检查文件是否存在

func FileSize

func FileSize(path string) (int64, error)

FileSize 获取文件大小

func FormatDate

func FormatDate(t time.Time) string

FormatDate 格式化为日期 "2006-01-02"

func FormatDateTime

func FormatDateTime(t time.Time) string

FormatDateTime 格式化为标准日期时间 "2006-01-02 15:04:05"

func FormatTime

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

FormatTime 格式化时间

func FormatTimeOnly

func FormatTimeOnly(t time.Time) string

FormatTimeOnly 格式化为时间 "15:04:05"

func FromTimestamp

func FromTimestamp(timestamp int64) time.Time

FromTimestamp 毫秒时间戳转 time.Time

func FromUnix

func FromUnix(unix int64) time.Time

FromUnix 秒级时间戳转 time.Time

func GetDateInt

func GetDateInt(t time.Time) int

GetDateInt 返回 yyyyMMdd 格式的日期整数

func HTTPGet

func HTTPGet(url string, params map[string]string) ([]byte, error)

HTTPGet 使用默认客户端发送 GET 请求。

func HTTPPost

func HTTPPost(url string, params map[string]string) ([]byte, error)

HTTPPost 使用默认客户端发送表单 POST 请求。

func HTTPPostJSON

func HTTPPostJSON(url string, data any) ([]byte, error)

HTTPPostJSON 使用默认客户端发送 JSON POST 请求。

func HasChinese

func HasChinese(s string) bool

HasChinese 检查字符串是否包含中文字符

func HashFile

func HashFile(path string, newHash func() hash.Hash) (string, error)

HashFile 流式计算文件的哈希值,返回 hex 编码字符串。

newHash 须返回全新的 hash.Hash 实例(如 sha256.New),本函数不复用它。 Open 或读取失败时返回错误。M-F 修复:改为流式 io.Copy(h, f),不再经 ReadFile 把整文件 读入内存——原实现大文件 OOM。流式哈希内存占用恒定、可处理任意大小文件,与 hash.Hash 的 io.Writer 接口契合。调用方负责选择哈希算法(如 sha256.New)。

func IsAllBlank

func IsAllBlank(strs ...string) bool

IsAllBlank 检查所有字符串是否都为空或空白

func IsAlpha

func IsAlpha(s string) bool

IsAlpha 检查字符串是否全部为字母

func IsAlphanumeric

func IsAlphanumeric(s string) bool

IsAlphanumeric 检查字符串是否全部为字母或数字

func IsAnyBlank

func IsAnyBlank(strs ...string) bool

IsAnyBlank 检查多个字符串中是否有任意一个为空或空白

func IsBlank

func IsBlank(s string) bool

IsBlank 检查字符串是否为空或仅包含空白字符

func IsChinese

func IsChinese(s string) bool

IsChinese 检查字符串是否非空且全部为中文字符(CJK 基本区 U+4E00..U+9FFF)。空串返回 false。

func IsEmail

func IsEmail(email string) bool

IsEmail 检查是否为有效的邮箱地址

func IsEmpty

func IsEmpty(v any) bool

IsEmpty 检查任意类型是否为空值。

实际支持(N4 文档修正):nil、空 string、空 []byte。 注意:通用 []T / map[K]V 走 default 分支恒返回 false(不为空)——若需对任意 slice/map 判空,请用 len() 显式判断。文档原称支持 slice/map 与实现不符,已修正。

func IsIDCard

func IsIDCard(id string) bool

IsIDCard 检查是否为有效的中国身份证号(18位) 注意: 仅校验格式,不校验校验位

func IsIPv4

func IsIPv4(ip string) bool

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

func IsNotBlank

func IsNotBlank(s string) bool

IsNotBlank 检查字符串是否非空且不全是空白字符

func IsNumeric

func IsNumeric(s string) bool

IsNumeric 检查字符串是否全部为数字

func IsPhone

func IsPhone(phone string) bool

IsPhone 检查是否为有效的中国大陆手机号 注意: 正则基于当前号段,新号段开放时需更新

func JSONMarshal

func JSONMarshal(v any) ([]byte, error)

JSONMarshal 将 v 序列化为 JSON。

func MD5

func MD5(s string) string

MD5 计算字符串的 MD5 哈希值 注意: 不应用于密码存储

func MD5Bytes

func MD5Bytes(data []byte) string

MD5Bytes 计算字节数组的 MD5 哈希值

func Nl2br

func Nl2br(s string, isXhtml bool) string

Nl2br 将换行符替换为 <br> 标签

func NowTimestamp

func NowTimestamp() int64

NowTimestamp 返回当前毫秒时间戳

func NowUnix

func NowUnix() int64

NowUnix 返回当前秒级时间戳

func ParseDateInt

func ParseDateInt(date int) time.Time

ParseDateInt 将 yyyyMMdd 格式的整数转为时间(当日 00:00:00,本地时区)。

注意:非法输入(如 month=13、day=32)会被 time.Date 静默规范化(溢出进位), 调用方需自行保证输入合法或在使用前校验(M4)。

func ParseTime

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

ParseTime 解析时间字符串

func RandDigitSecure added in v1.2.0

func RandDigitSecure(n int) (string, error)

RandDigitSecure 生成指定长度的密码学安全随机数字字符串。 基于 crypto/rand,不可预测,适用于 OTP 验证码、密码重置码等安全场景。 n<=0 返回空,n 过大(>1<<20)返回错误。

func RandInt

func RandInt(min, max int) int

RandInt 返回 [min, max) 范围内的随机整数。min==max 时返回 min;max<min 自动交换。

非密码学安全(math/rand + sync.Pool),仅用于非安全场景(负载均衡、游戏、A/B 分桶等); 不适用于 token/OTP 等安全场景。

func RandInt64

func RandInt64(min, max int64) int64

RandInt64 返回 [min, max) 范围内的随机 int64(非密码学安全)。min==max 返回 min;max<min 自动交换。

func RandInt64Secure added in v1.2.0

func RandInt64Secure(min, max int64) (int64, error)

RandInt64Secure 返回 [min, max) 范围内的密码学安全随机 int64。 基于 crypto/rand + big.Int 拒绝采样(无偏)。min==max 返回 min;max<min 自动交换。

func RandIntSecure added in v1.2.0

func RandIntSecure(min, max int) (int, error)

RandIntSecure 返回 [min, max) 范围内的密码学安全随机整数。 基于 crypto/rand + big.Int 拒绝采样(无偏),适用于安全 nonce 范围、防猜抽奖、密钥分桶等。 min==max 返回 min;max<min 自动交换。crypto/rand 读取失败时返回错误。

func RandStringSecure added in v1.2.0

func RandStringSecure(n int) (string, error)

RandStringSecure 生成指定长度的密码学安全随机字符串(字母+数字)。 基于 crypto/rand,不可预测,适用于 token、会话 ID、API key 等安全场景。 n<=0 返回空,n 过大(>1<<20)返回错误避免过度消耗熵池。

func ReadFile

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

ReadFile 读取文件内容。

M-F 修复:去掉前置 FileExists 检查(TOCTOU 竞态——检查与读取之间文件可能被删除/替换), 直接 os.ReadFile 并返回其错误。文件不存在时返回 *os.PathError,调用方可经 errors.Is(err, os.ErrNotExist) 精确判断。

注意:本函数无大小上限(os.ReadFile 语义),读取不可信/超大文件有 OOM 风险—— 需限长读取请用 io.ReadAll(io.LimitReader(...));流式哈希大文件请用 HashFile(已流式)。

func RemoveFile

func RemoveFile(path string) error

RemoveFile 删除文件(忽略不存在的错误)

func SHA1

func SHA1(s string) string

SHA1 计算字符串的 SHA1 哈希值 注意: 不应用于密码存储

func SHA256

func SHA256(s string) string

SHA256 计算字符串的 SHA256 哈希值

func SHA256Bytes

func SHA256Bytes(data []byte) string

SHA256Bytes 计算字节数组的 SHA256 哈希值

func StartOfDay

func StartOfDay(t time.Time) time.Time

StartOfDay 返回指定时间当天的开始时间 (00:00:00)

func StartOfMonth

func StartOfMonth(t time.Time) time.Time

StartOfMonth 返回指定时间当月 1 日 00:00:00(保留原时区)。

func StartOfWeek

func StartOfWeek(t time.Time) time.Time

StartOfWeek 返回指定时间当周的开始时间(周一为第一天,00:00:00)。

用日历日回退而非 t.Add(-N*24h),避免 DST 切换日 24h ≠ 1 个日历日导致落错日(M4)。

func StrLen

func StrLen(s string) int

StrLen 获取字符串的 Unicode 字符数

func Substr

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

Substr 截取子字符串(按 Unicode 字符计数)。 start 支持负数(从末尾计算);start 越界或 length<=0 返回空串;length 超出末尾自动截断。 参数: start 起始位置(支持负数从末尾计算),length 截取长度

func ToFloat64

func ToFloat64(s string) float64

ToFloat64 字符串转 float64,失败返回 0

func ToFloat64Default

func ToFloat64Default(s string, def float64) float64

ToFloat64Default 字符串转 float64,失败返回默认值

func ToInt

func ToInt(s string) int

ToInt 字符串转 int,失败返回 0

func ToInt64

func ToInt64(s string) int64

ToInt64 字符串转 int64,失败返回 0

func ToInt64Default

func ToInt64Default(s string, def int64) int64

ToInt64Default 字符串转 int64,失败返回默认值

func ToInt64E added in v1.3.0

func ToInt64E(s string) (int64, error)

ToInt64E converts a string to int64 and returns parse errors. Prefer it when 0 is a meaningful value and parse failure must be distinguishable.

func ToIntDefault

func ToIntDefault(s string, def int) int

ToIntDefault 字符串转 int,失败返回默认值

func ToIntE added in v1.3.0

func ToIntE(s string) (int, error)

ToIntE converts a string to int and returns parse errors. Prefer it when 0 is a meaningful value and parse failure must be distinguishable.

func ToString

func ToString(n int) string

ToString 整数转字符串

func ToString64

func ToString64(n int64) string

ToString64 int64 转字符串

func ToUint64

func ToUint64(s string) uint64

ToUint64 字符串转 uint64,失败返回 0

func ToUint64Default

func ToUint64Default(s string, def uint64) uint64

ToUint64Default 字符串转 uint64,失败返回默认值

func Trim

func Trim(s string) string

Trim 去除字符串首尾的空白字符(包括空格、制表符、换行符)

func URLDecode

func URLDecode(s string) (string, error)

URLDecode URL 解码

func URLEncode

func URLEncode(s string) string

URLEncode URL 编码

func UUID

func UUID() string

UUID 生成 UUID v4 字符串

func UUIDParse

func UUIDParse(s string) (uuid.UUID, error)

UUIDParse 解析 UUID 字符串

func UUIDShort

func UUIDShort() string

UUIDShort 生成短 UUID(无横线,32 个十六进制字符)

func UUIDValid

func UUIDValid(s string) bool

UUIDValid 检查 UUID 字符串是否有效

func WriteFile

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

WriteFile 写入文件内容(覆盖)

Types

type HTTPClient

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

HTTPClient 封装可运行期调整配置的 HTTP 客户端。

func DefaultHTTPClient

func DefaultHTTPClient() *HTTPClient

DefaultHTTPClient 返回包级共享 HTTP 客户端。

func NewHTTPClient

func NewHTTPClient() *HTTPClient

NewHTTPClient 使用默认配置创建 HTTP 客户端。

func NewHTTPClientWithConfig

func NewHTTPClientWithConfig(cfg HTTPClientConfig) *HTTPClient

NewHTTPClientWithConfig 使用 cfg 创建 HTTP 客户端。

func NewSSRFSafeHTTPClient added in v1.2.0

func NewSSRFSafeHTTPClient() *HTTPClient

NewSSRFSafeHTTPClient 创建启用 SSRF 防护的 HTTP 客户端。

func (*HTTPClient) Close

func (c *HTTPClient) Close()

Close 释放客户端 transport 持有的空闲连接。

func (*HTTPClient) Delete

func (c *HTTPClient) Delete(urlStr string) ([]byte, error)

Delete 发送 DELETE 请求。

func (*HTTPClient) DoWithResponse

func (c *HTTPClient) DoWithResponse(req *http.Request) (*http.Response, error)

DoWithResponse 执行 req 并返回原始响应;调用方必须关闭 resp.Body。

func (*HTTPClient) Get

func (c *HTTPClient) Get(urlStr string, params map[string]string) ([]byte, error)

Get 发送 GET 请求。

func (*HTTPClient) Post

func (c *HTTPClient) Post(urlStr string, params map[string]string) ([]byte, error)

Post 发送表单编码的 POST 请求。

func (*HTTPClient) PostJSON

func (c *HTTPClient) PostJSON(urlStr string, data any) ([]byte, error)

PostJSON 发送 JSON POST 请求。

func (*HTTPClient) Put

func (c *HTTPClient) Put(urlStr string, data any) ([]byte, error)

Put 发送 JSON PUT 请求。

func (*HTTPClient) Request

func (c *HTTPClient) Request(method, urlStr string, body []byte) ([]byte, error)

Request 使用调用方指定的方法和 JSON 请求体发送请求。

func (*HTTPClient) SetBlockPrivateNetworks added in v1.2.0

func (c *HTTPClient) SetBlockPrivateNetworks(block bool) *HTTPClient

SetBlockPrivateNetworks 切换后续请求的 SSRF 防护。

func (*HTTPClient) SetCookie

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

SetCookie 设置后续请求使用的 Cookie。

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

func (c *HTTPClient) SetSkipTLS(skip bool) *HTTPClient

SetSkipTLS 切换后续请求是否校验 TLS 证书。

func (*HTTPClient) SetTimeout

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

SetTimeout 更新请求超时时间,并保留当前 transport。

func (*HTTPClient) Upload

func (c *HTTPClient) Upload(urlStr string, files []UploadFile, params map[string]string) ([]byte, error)

Upload 以流式 multipart 上传文件,避免把完整请求体缓存在内存中。

func (*HTTPClient) UploadFromBytes

func (c *HTTPClient) UploadFromBytes(urlStr string, fieldName string, filename string, data []byte, params map[string]string) ([]byte, error)

UploadFromBytes 将内存中的字节切片作为 multipart 文件上传。

type HTTPClientConfig

type HTTPClientConfig struct {
	Timeout              time.Duration
	MaxIdleConns         int
	IdleConnTimeout      time.Duration
	MaxConnsPerHost      int
	MaxIdleConnsPerHost  int
	SkipTLSVerify        bool
	MaxResponseBodySize  int64
	BlockPrivateNetworks bool
}

HTTPClientConfig 是 HTTPClient 的配置。

type URLBuilder

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

URLBuilder URL 构建器

func ParseURL

func ParseURL(rawURL string) (*URLBuilder, error)

ParseURL 解析 URL 字符串

func (*URLBuilder) AddQueries

func (b *URLBuilder) AddQueries(params map[string]string) *URLBuilder

AddQueries 批量添加查询参数(追加,同 key 多值共存,M2 修复:原实现用 Set 会覆盖)。 params 为 nil 时无操作(遍历 nil map 安全,不 panic)。

func (*URLBuilder) AddQuery

func (b *URLBuilder) AddQuery(key, value string) *URLBuilder

AddQuery 添加单个查询参数

func (*URLBuilder) Build

func (b *URLBuilder) Build() *url.URL

Build 构建最终的 URL

func (*URLBuilder) SetHost

func (b *URLBuilder) SetHost(host string) *URLBuilder

SetHost 设置主机

func (*URLBuilder) SetPath

func (b *URLBuilder) SetPath(path string) *URLBuilder

SetPath 设置路径

func (*URLBuilder) SetQuery

func (b *URLBuilder) SetQuery(key, value string) *URLBuilder

SetQuery 设置查询参数(覆盖同名参数)

func (*URLBuilder) SetScheme

func (b *URLBuilder) SetScheme(scheme string) *URLBuilder

SetScheme 设置协议(http/https)

func (*URLBuilder) String

func (b *URLBuilder) String() string

String 返回 URL 字符串

type UploadFile

type UploadFile struct {
	FieldName string
	FilePath  string
}

UploadFile 描述 multipart 上传中的文件字段。

Jump to

Keyboard shortcuts

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