Documentation
¶
Index ¶
- Variables
- func AppendFile(path string, data []byte) error
- func Base64Decode(s string) ([]byte, error)
- func Base64Encode(data []byte) string
- func Base64URLDecode(s string) ([]byte, error)
- func Base64URLEncode(data []byte) string
- func CalcOffset(page, pageSize int) int
- func CalcPageCount(total, pageSize int64) int64
- func CopyFile(dst, src string) error
- func DefaultIfBlank(s, def string) string
- func DirExists(path string) bool
- func EndOfDay(t time.Time) time.Time
- func EndOfMonth(t time.Time) time.Time
- func EnsureDir(path string) error
- func EqualsIgnoreCase(a, b string) bool
- func FileExists(path string) bool
- func FileSize(path string) (int64, error)
- func FormatDate(t time.Time) string
- func FormatDateTime(t time.Time) string
- func FormatTime(t time.Time, layout string) string
- func FormatTimeOnly(t time.Time) string
- func FromTimestamp(timestamp int64) time.Time
- func FromUnix(unix int64) time.Time
- func GetDateInt(t time.Time) int
- func HTTPGet(url string, params map[string]string) ([]byte, error)
- func HTTPPost(url string, params map[string]string) ([]byte, error)
- func HTTPPostJSON(url string, data any) ([]byte, error)
- func HasChinese(s string) bool
- func HashFile(path string, newHash func() hash.Hash) (string, error)
- func IsAllBlank(strs ...string) bool
- func IsAlpha(s string) bool
- func IsAlphanumeric(s string) bool
- func IsAnyBlank(strs ...string) bool
- func IsBlank(s string) bool
- func IsChinese(s string) bool
- func IsEmail(email string) bool
- func IsEmpty(v any) bool
- func IsIDCard(id string) bool
- func IsIPv4(ip string) bool
- func IsNotBlank(s string) bool
- func IsNumeric(s string) bool
- func IsPhone(phone string) bool
- func JSONMarshal(v any) ([]byte, error)
- func MD5(s string) string
- func MD5Bytes(data []byte) string
- func Nl2br(s string, isXhtml bool) string
- func NowTimestamp() int64
- func NowUnix() int64
- func ParseDateInt(date int) time.Time
- func ParseTime(timeStr, layout string) (time.Time, error)
- func RandDigitSecure(n int) (string, error)
- func RandInt(min, max int) int
- func RandInt64(min, max int64) int64
- func RandInt64Secure(min, max int64) (int64, error)
- func RandIntSecure(min, max int) (int, error)
- func RandStringSecure(n int) (string, error)
- func ReadFile(path string) ([]byte, error)
- func RemoveFile(path string) error
- func SHA1(s string) string
- func SHA256(s string) string
- func SHA256Bytes(data []byte) string
- func StartOfDay(t time.Time) time.Time
- func StartOfMonth(t time.Time) time.Time
- func StartOfWeek(t time.Time) time.Time
- func StrLen(s string) int
- func Substr(s string, start, length int) string
- func ToFloat64(s string) float64
- func ToFloat64Default(s string, def float64) float64
- func ToInt(s string) int
- func ToInt64(s string) int64
- func ToInt64Default(s string, def int64) int64
- func ToInt64E(s string) (int64, error)
- func ToIntDefault(s string, def int) int
- func ToIntE(s string) (int, error)
- func ToString(n int) string
- func ToString64(n int64) string
- func ToUint64(s string) uint64
- func ToUint64Default(s string, def uint64) uint64
- func Trim(s string) string
- func URLDecode(s string) (string, error)
- func URLEncode(s string) string
- func UUID() string
- func UUIDParse(s string) (uuid.UUID, error)
- func UUIDShort() string
- func UUIDValid(s string) bool
- func WriteFile(path string, data []byte) error
- type HTTPClient
- func (c *HTTPClient) Close()
- func (c *HTTPClient) Delete(urlStr string) ([]byte, error)
- func (c *HTTPClient) DoWithResponse(req *http.Request) (*http.Response, error)
- func (c *HTTPClient) Get(urlStr string, params map[string]string) ([]byte, error)
- func (c *HTTPClient) Post(urlStr string, params map[string]string) ([]byte, error)
- func (c *HTTPClient) PostJSON(urlStr string, data any) ([]byte, error)
- func (c *HTTPClient) Put(urlStr string, data any) ([]byte, error)
- func (c *HTTPClient) Request(method, urlStr string, body []byte) ([]byte, error)
- func (c *HTTPClient) SetBlockPrivateNetworks(block bool) *HTTPClient
- func (c *HTTPClient) SetCookie(key, value string) *HTTPClient
- func (c *HTTPClient) SetHeader(key, value string) *HTTPClient
- func (c *HTTPClient) SetHeaders(headers map[string]string) *HTTPClient
- func (c *HTTPClient) SetSkipTLS(skip bool) *HTTPClient
- func (c *HTTPClient) SetTimeout(timeout time.Duration) *HTTPClient
- func (c *HTTPClient) Upload(urlStr string, files []UploadFile, params map[string]string) ([]byte, error)
- func (c *HTTPClient) UploadFromBytes(urlStr string, fieldName string, filename string, data []byte, ...) ([]byte, error)
- type HTTPClientConfig
- type URLBuilder
- func (b *URLBuilder) AddQueries(params map[string]string) *URLBuilder
- func (b *URLBuilder) AddQuery(key, value string) *URLBuilder
- func (b *URLBuilder) Build() *url.URL
- func (b *URLBuilder) SetHost(host string) *URLBuilder
- func (b *URLBuilder) SetPath(path string) *URLBuilder
- func (b *URLBuilder) SetQuery(key, value string) *URLBuilder
- func (b *URLBuilder) SetScheme(scheme string) *URLBuilder
- func (b *URLBuilder) String() string
- type UploadFile
Constants ¶
This section is empty.
Variables ¶
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 客户端配置。
var ErrRandInvalidLength = errors.New("invalid random length")
ErrRandInvalidLength 长度过大(超过 1<<20,保护熵池)。n<=0 时返回空串而非此错误。
var ErrSSRFBlocked = errors.New("ssrf guard: 目标 IP 属于被拦截的网络范围")
ErrSSRFBlocked 表示 SSRF 防护拦截了目标 IP。
Functions ¶
func Base64URLDecode ¶
Base64URLDecode URL 安全的 Base64 解码
func CalcOffset ¶
CalcOffset 计算分页偏移量 (page-1)*pageSize。page<=0 时按 1 处理,pageSize<=0 时按 20 处理。
func CalcPageCount ¶
CalcPageCount 计算总页数(向上取整)。total<=0 或 pageSize<=0 时返回 0。
func EndOfMonth ¶
EndOfMonth 返回指定时间当月最后一天 23:59:59.999999999(保留原时区)。
func EqualsIgnoreCase ¶
EqualsIgnoreCase 不区分大小写比较字符串。
L-C 修复:改用 strings.EqualFold(标准库 Unicode 大小写折叠)。原实现仅做 ASCII 字节级折叠('A'-'Z' → +32),对非 ASCII 字符(如 "É" vs "é")误判为不等。 EqualFold 同时更快(无逐字节循环开销)。
func FormatDateTime ¶
FormatDateTime 格式化为标准日期时间 "2006-01-02 15:04:05"
func HTTPPostJSON ¶
HTTPPostJSON 使用默认客户端发送 JSON POST 请求。
func HashFile ¶
HashFile 流式计算文件的哈希值,返回 hex 编码字符串。
newHash 须返回全新的 hash.Hash 实例(如 sha256.New),本函数不复用它。 Open 或读取失败时返回错误。M-F 修复:改为流式 io.Copy(h, f),不再经 ReadFile 把整文件 读入内存——原实现大文件 OOM。流式哈希内存占用恒定、可处理任意大小文件,与 hash.Hash 的 io.Writer 接口契合。调用方负责选择哈希算法(如 sha256.New)。
func IsEmpty ¶
IsEmpty 检查任意类型是否为空值。
实际支持(N4 文档修正):nil、空 string、空 []byte。 注意:通用 []T / map[K]V 走 default 分支恒返回 false(不为空)——若需对任意 slice/map 判空,请用 len() 显式判断。文档原称支持 slice/map 与实现不符,已修正。
func ParseDateInt ¶
ParseDateInt 将 yyyyMMdd 格式的整数转为时间(当日 00:00:00,本地时区)。
注意:非法输入(如 month=13、day=32)会被 time.Date 静默规范化(溢出进位), 调用方需自行保证输入合法或在使用前校验(M4)。
func RandDigitSecure ¶ added in v1.2.0
RandDigitSecure 生成指定长度的密码学安全随机数字字符串。 基于 crypto/rand,不可预测,适用于 OTP 验证码、密码重置码等安全场景。 n<=0 返回空,n 过大(>1<<20)返回错误。
func RandInt ¶
RandInt 返回 [min, max) 范围内的随机整数。min==max 时返回 min;max<min 自动交换。
非密码学安全(math/rand + sync.Pool),仅用于非安全场景(负载均衡、游戏、A/B 分桶等); 不适用于 token/OTP 等安全场景。
func RandInt64Secure ¶ added in v1.2.0
RandInt64Secure 返回 [min, max) 范围内的密码学安全随机 int64。 基于 crypto/rand + big.Int 拒绝采样(无偏)。min==max 返回 min;max<min 自动交换。
func RandIntSecure ¶ added in v1.2.0
RandIntSecure 返回 [min, max) 范围内的密码学安全随机整数。 基于 crypto/rand + big.Int 拒绝采样(无偏),适用于安全 nonce 范围、防猜抽奖、密钥分桶等。 min==max 返回 min;max<min 自动交换。crypto/rand 读取失败时返回错误。
func RandStringSecure ¶ added in v1.2.0
RandStringSecure 生成指定长度的密码学安全随机字符串(字母+数字)。 基于 crypto/rand,不可预测,适用于 token、会话 ID、API key 等安全场景。 n<=0 返回空,n 过大(>1<<20)返回错误避免过度消耗熵池。
func ReadFile ¶
ReadFile 读取文件内容。
M-F 修复:去掉前置 FileExists 检查(TOCTOU 竞态——检查与读取之间文件可能被删除/替换), 直接 os.ReadFile 并返回其错误。文件不存在时返回 *os.PathError,调用方可经 errors.Is(err, os.ErrNotExist) 精确判断。
注意:本函数无大小上限(os.ReadFile 语义),读取不可信/超大文件有 OOM 风险—— 需限长读取请用 io.ReadAll(io.LimitReader(...));流式哈希大文件请用 HashFile(已流式)。
func StartOfMonth ¶
StartOfMonth 返回指定时间当月 1 日 00:00:00(保留原时区)。
func StartOfWeek ¶
StartOfWeek 返回指定时间当周的开始时间(周一为第一天,00:00:00)。
用日历日回退而非 t.Add(-N*24h),避免 DST 切换日 24h ≠ 1 个日历日导致落错日(M4)。
func Substr ¶
Substr 截取子字符串(按 Unicode 字符计数)。 start 支持负数(从末尾计算);start 越界或 length<=0 返回空串;length 超出末尾自动截断。 参数: start 起始位置(支持负数从末尾计算),length 截取长度
func ToFloat64Default ¶
ToFloat64Default 字符串转 float64,失败返回默认值
func ToInt64Default ¶
ToInt64Default 字符串转 int64,失败返回默认值
func ToInt64E ¶ added in v1.3.0
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 ToIntE ¶ added in v1.3.0
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 ToUint64Default ¶
ToUint64Default 字符串转 uint64,失败返回默认值
Types ¶
type HTTPClient ¶
type HTTPClient struct {
// contains filtered or unexported fields
}
HTTPClient 封装可运行期调整配置的 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) Delete ¶
func (c *HTTPClient) Delete(urlStr string) ([]byte, error)
Delete 发送 DELETE 请求。
func (*HTTPClient) DoWithResponse ¶
DoWithResponse 执行 req 并返回原始响应;调用方必须关闭 resp.Body。
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 上传文件,避免把完整请求体缓存在内存中。
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 (*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) SetQuery ¶
func (b *URLBuilder) SetQuery(key, value string) *URLBuilder
SetQuery 设置查询参数(覆盖同名参数)
func (*URLBuilder) SetScheme ¶
func (b *URLBuilder) SetScheme(scheme string) *URLBuilder
SetScheme 设置协议(http/https)
type UploadFile ¶
UploadFile 描述 multipart 上传中的文件字段。