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 ToIntDefault(s string, def int) int
- 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 默认配置
var ErrRandInvalidLength = errors.New("invalid random length")
ErrRandInvalidLength 长度过大(超过 1<<20,保护熵池)。n<=0 时返回空串而非此错误。
var ErrSSRFBlocked = errors.New("ssrf guard: 目标 IP 属被拦截网段(回环/私有/链路本地/元数据)")
ErrSSRFBlocked 目标 IP 落在被拦截网段(SSRF 防护,P0)。
Functions ¶
func Base64URLDecode ¶
Base64URLDecode URL 安全的 Base64 解码
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 计算文件的哈希值。
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) 范围内的随机整数。
非密码学安全(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 StartOfWeek ¶
StartOfWeek 返回指定时间当周的开始时间(周一为第一天,00:00:00)。
用日历日回退而非 t.Add(-N*24h),避免 DST 切换日 24h ≠ 1 个日历日导致落错日(M4)。
func ToFloat64Default ¶
ToFloat64Default 字符串转 float64,失败返回默认值
func ToInt64Default ¶
ToInt64Default 字符串转 int64,失败返回默认值
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 使用自定义配置创建 HTTP 客户端
func NewSSRFSafeHTTPClient ¶ added in v1.2.0
func NewSSRFSafeHTTPClient() *HTTPClient
NewSSRFSafeHTTPClient 创建启用 SSRF 防护的 HTTP 客户端(P0):拒绝连接内网目标 IP。 适用于目标 URL 可能来自用户输入的场景(webhook 回调、远程图片抓取等)。
func (*HTTPClient) Delete ¶
func (c *HTTPClient) Delete(urlStr string) ([]byte, error)
Delete 发送 DELETE 请求
func (*HTTPClient) DoWithResponse ¶
DoWithResponse 执行请求并返回完整响应。
注意:调用方负责关闭返回的 resp.Body;且此方法不套用 maxRespBodySize 读封顶(由调用方掌控)。
func (*HTTPClient) PostJSON ¶
func (c *HTTPClient) PostJSON(urlStr string, data any) ([]byte, error)
PostJSON 发送 POST 请求(JSON 格式)
func (*HTTPClient) Put ¶
func (c *HTTPClient) Put(urlStr string, data any) ([]byte, error)
Put 发送 PUT 请求(JSON 格式)
func (*HTTPClient) Request ¶
func (c *HTTPClient) Request(method, urlStr string, body []byte) ([]byte, error)
Request 发送自定义请求
func (*HTTPClient) SetBlockPrivateNetworks ¶ added in v1.2.0
func (c *HTTPClient) SetBlockPrivateNetworks(block bool) *HTTPClient
SetBlockPrivateNetworks 运行期开关 SSRF 防护(P0)。开启后连接内网 IP(回环/私有/链路本地/ 元数据等)会被拒绝并返回 ErrSSRFBlocked。写锁下重建 transport+client 并原子替换, 与并发请求无竞态;旧 transport 的空闲连接在锁外释放。
func (*HTTPClient) SetCookie ¶
func (c *HTTPClient) SetCookie(key, value string) *HTTPClient
SetCookie 设置 Cookie(P0:写锁保护)。
func (*HTTPClient) SetHeader ¶
func (c *HTTPClient) SetHeader(key, value string) *HTTPClient
SetHeader 设置请求头(P0:写锁保护,与并发 do/DoWithResponse 读 map 无竞态)。
func (*HTTPClient) SetHeaders ¶
func (c *HTTPClient) SetHeaders(headers map[string]string) *HTTPClient
SetHeaders 批量设置请求头(P0:写锁保护)。
func (*HTTPClient) SetSkipTLS ¶
func (c *HTTPClient) SetSkipTLS(skip bool) *HTTPClient
SetSkipTLS 设置是否跳过 TLS 验证。 跳过 TLS 校验会暴露于 MITM 攻击,仅在受控环境(如自签证书的内网服务)且明确风险时启用, 生产环境应保持 false。
H-12 修复:原实现直接覆盖 c.transport.TLSClientConfig 指针,与并发 Do 读取该字段 存在数据竞争(-race 必采),且注释自承"需重建 Transport"却未重建。改为在写锁下用 新配置重建 transport+client 并原子替换,旧 transport 释放空闲连接(保留旧 TLS 配置的 idle 连接不再被复用)。支持运行期并发调用与并发请求无竞态。
func (*HTTPClient) SetTimeout ¶
func (c *HTTPClient) SetTimeout(timeout time.Duration) *HTTPClient
SetTimeout 设置超时时间。 H-12 修复:在写锁下重建 *http.Client(复用 transport 保留连接池),避免与并发 Do 对 client.Timeout 字段的数据竞争。
func (*HTTPClient) Upload ¶
func (c *HTTPClient) Upload(urlStr string, files []UploadFile, params map[string]string) ([]byte, error)
Upload 上传文件
type HTTPClientConfig ¶
type HTTPClientConfig struct {
Timeout time.Duration // 请求超时时间
MaxIdleConns int // 最大空闲连接数
IdleConnTimeout time.Duration // 空闲连接超时时间
MaxConnsPerHost int // 每个主机最大连接数
MaxIdleConnsPerHost int // 每个主机最大空闲连接数
SkipTLSVerify bool // 是否跳过 TLS 验证(默认 false 校验 TLS;自签证书场景需显式设 true)
// MaxResponseBodySize 响应体读取上限(字节)。0 = 默认 32MB,-1 = 不限制。
// 防止异常服务端返回超大响应打爆内存(C5/N5)。
MaxResponseBodySize int64
// BlockPrivateNetworks 启用 SSRF 防护(P0,默认 false 保持兼容)。启用后,连接建立时
// 校验解析出的目标 IP,拒绝回环/私有(RFC1918+ULA)/链路本地/元数据(169.254.169.254)/
// 未指定/多播等内网地址。校验在 DialContext.Control 中进行,对重定向的每一跳同样生效。
// 当 URL 可能来自用户输入(webhook、头像抓取等)时应开启。
BlockPrivateNetworks bool
}
HTTPClientConfig HTTP 客户端配置
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 上传文件信息