Documentation
¶
Overview ¶
Package network Client 提供实例化的 HTTP 客户端。
每个 Client 持有独立的 TLS 配置、Transport 缓存与 retryablehttp.Client 缓存, 多个 Engine / Runner 可并发使用各自实例,互不干扰。
Package network 提供 HTTP 请求、协议探测与请求解析工具。
- Package request @Author: zhizhuo @IDE:GoLand @File: network.go @Date: 2025/1/8 下午2:39*
Package network per-host rate limiter。
每个目标主机(可选按端口细分)独立持有一个 *rate.Limiter(令牌桶), 使用 phuslu/lru 作为 LRU 容器(容量 hostLimiterCacheSize), 过期 host 自动 evict;Limiter 在 host 首次访问时才创建。
完全实例化:调用方 NewHostRateLimiter(qps, burst) 创建并持有, 不存在任何包级 limiter。
Package request @Author: zhizhuo @IDE:GoLand @File: raw.go @Date: 2025/2/8 下午4:02*
Package request @Author: zhizhuo @IDE:GoLand @File: raw_http.go @Date: 2025/2/8 下午4:05*
Package request @Author: zhizhuo @IDE:GoLand @File: raw_parse.go @Date: 2025/2/20 上午10:32*
Index ¶
- Constants
- func AssignVariableRaw(find string, variableMap map[string]any) string
- func CheckProxy(ctx context.Context, proxyURL, address string, timeout time.Duration) error
- func DialContext(ctx context.Context, network, address, proxyURL string, timeout time.Duration, ...) (net.Conn, error)
- func KeepPortableHeaders(header http.Header)
- func NewGlobalRateLimiter(perSecond float64, burst int) *rate.Limiter
- func Origin(u *url.URL) string
- func RawParse(nc *Client, data []byte, res []byte, variableMap map[string]any) error
- func ReadResponseBody(resp *http.Response, limit int64) ([]byte, error)
- func SameOrigin(a, b *url.URL) bool
- func SendRawRequest(ctx context.Context, client *HTTPClient, request, baseurl string, ...) error
- func TargetCandidates(target string) (candidates []string, samePort bool)
- func Url2ProtoUrl(u *url.URL) *proto.UrlType
- func ValidateProxyURL(raw string) (*url.URL, error)
- func WithConnectProbe(ctx context.Context) (context.Context, func() bool)
- func WithCookieJar(ctx context.Context) context.Context
- type Client
- type Endpoint
- type HTTPClient
- func (c *HTTPClient) Close() error
- func (c *HTTPClient) GetResource(ctx context.Context, rawURL string, options OptionsRequest) (*http.Response, error)
- func (c *HTTPClient) ResourceCookies(ctx context.Context, rawURL string) []*http.Cookie
- func (c *HTTPClient) ResourceHash(key [32]byte) (string, bool)
- func (c *HTTPClient) SendRawRequest(ctx context.Context, rawText, baseURL string, options OptionsRequest) (*http.Response, error)
- func (c *HTTPClient) SendRequestHttp(ctx context.Context, method, urlStr, body string, options OptionsRequest) (*http.Response, error)
- func (c *HTTPClient) SetDisableKeepAlives(disabled bool)
- func (c *HTTPClient) SetGlobalRateLimiter(limiter *rate.Limiter)
- func (c *HTTPClient) SetHTTPDebug(enabled bool)
- func (c *HTTPClient) SetInsecureSkipVerify(skip bool)
- func (c *HTTPClient) SetRateLimiter(limiter *HostRateLimiter)
- func (c *HTTPClient) StoreResourceHash(key [32]byte, hash string)
- func (c *HTTPClient) WaitRequest(ctx context.Context, target string) error
- type HostRateLimiter
- type OptionsRequest
- type ProxyError
- type Request
- type TcpOrUdpConfig
Constants ¶
const ( MaxDefaultBody int64 = 512 * 1024 DefaultTimeout = 10 * time.Second HttpPrefix = "http://" HttpsPrefix = "https://" )
请求体与超时默认值。
const ( DefaultNetwork = "tcp" DefaultDialTimeout = 5 * time.Second DefaultWriteTimeout = 5 * time.Second DefaultReadTimeout = 5 * time.Second DefaultRetryDelay = 2 * time.Second DefaultReadSize = 2048 DefaultMaxRetries = 3 // TCP 收到首段数据后等待后续数据的空闲时间范围。未显式配置时取首段到达 // 耗时的两倍并限制在该范围内:往返越慢的连接,分段之间的间隔通常也越长。 MinReadIdle = 100 * time.Millisecond MaxReadIdle = time.Second )
Variables ¶
This section is empty.
Functions ¶
func CheckProxy ¶ added in v1.7.0
CheckProxy 经代理向 address(host:port)建立一次连接,只在代理本身不可用时返回 错误;目标不可达不算。用于在批量扫描开始前发现配置错误的代理。
func DialContext ¶
func DialContext(ctx context.Context, network, address, proxyURL string, timeout time.Duration, useTLS bool, serverName string, insecure bool) (net.Conn, error)
DialContext 保持代理、取消和 TLS 策略在初次连接与重试时一致。 支持 TCP/UDP 经 HTTP、SOCKS5、SOCKS5h 代理(UDP 仅 SOCKS5 系)。
func KeepPortableHeaders ¶ added in v1.7.0
KeepPortableHeaders 只保留可以发给任何主机的通用请求头,删除其余全部请求头。 请求因重定向离开原来的源时使用:自定义请求头可能带有令牌或内网信息。
func NewGlobalRateLimiter ¶ added in v1.6.0
NewGlobalRateLimiter 创建引擎级的总速率限制:实例发出的全部请求(入口、规则、 TCP/UDP、图标与重定向的每一跳)合计不超过 perSecond。burst 为瞬时突发上限, 非正值时取 1,即严格按速率匀速发出。perSecond 非正时返回 nil(不限制)。
func Origin ¶ added in v1.5.0
Origin 返回 URL 的规范化源 "scheme://host:port":协议与主机小写, 省略的端口按协议补全。不是 http/https 或缺少主机时返回空串。
func ReadResponseBody ¶
ReadResponseBody 在字节上限内读取响应。长度声明只用于容量提示;未知 长度使用分段暂存,EOF 后一次合并,不把可复用的暂存区交给调用方。
func SendRawRequest ¶
func SendRawRequest(ctx context.Context, client *HTTPClient, request, baseurl string, variableMap map[string]any, options OptionsRequest) error
SendRawRequest 发送当前实例的原始 HTTP 报文,遵循其取消、代理、TLS 和超时配置。
func TargetCandidates ¶ added in v1.5.0
TargetCandidates 返回目标可能对应的完整地址,按尝试顺序排列。 已带协议的目标只有它自身;未带协议时端口 80 只尝试 http,端口 443 只尝试 https,其余先 https 后 http。samePort 表示各候选连接的是同一个 TCP 端口, 此时连接失败无需再尝试另一个协议。
func Url2ProtoUrl ¶
Url2ProtoUrl 将 net/url.URL 转为 proto.UrlType。
func ValidateProxyURL ¶ added in v1.3.0
ValidateProxyURL 校验代理地址是否受支持,返回归一化后的 URL。空字符串视为直连(返回 nil, nil)。
func WithConnectProbe ¶ added in v1.5.0
WithConnectProbe 跟踪 ctx 下的请求是否建立过 TCP 连接。
目标未写协议且带端口时,https 与 http 连接的是同一个端口:TCP 连接失败说明 端口不可达,换协议只会再等一次超时;连接成功而握手或读取失败才值得改用 http。 经代理时连接的是代理,探针恒为已连接,调用方会照常尝试两种协议。
Types ¶
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client 客户端结构体
func NewClientContext ¶
NewClientContext 将连接、TLS 握手和读写统一绑定到调用方的生命周期。
type Endpoint ¶ added in v1.4.0
type Endpoint struct {
Host string // 主机名或 IP 字面量;IPv6 不带方括号,zone 以 % 分隔
Port string
TLS bool // 是否在连接上进行 TLS 握手;UDP 恒为 false
}
Endpoint 是 TCP/UDP 连接地址解析后的拨号端点。
func ParseEndpoint ¶ added in v1.4.0
ParseEndpoint 是 TCP/UDP 连接地址的唯一解析入口,同时决定主机、端口与是否握手, 使拨号地址、TLS 与 ServerName 不会由多处各自推断而互相矛盾。
地址形式:
host host:port [host]:port scheme://host scheme://host:port scheme://[host]:port/path
scheme 可为 tcp、udp、http(明文)或 https、tls、ssl(TLS)。带 scheme 的地址 允许携带用户信息、路径与查询(规则未写 host 时直接使用扫描目标 URL),解析时 只取主机和端口;不带 scheme 的地址只能是主机和端口。
方括号用于界定主机:IPv6 字面量必须加方括号,域名与 IPv4 也可以加, 因此 "[{{domain}}]:22" 对任何目标都没有歧义。未加方括号且含多个冒号的地址 无法区分地址与端口("2001:db8::1:80" 有两种读法),一律拒绝。
TLS 与缺省端口:https/tls/ssl 握手、缺省 443;http/tcp/udp 明文、缺省 80; 不带 scheme 时端口 443 或未写端口视为 TLS(缺省 443),其余端口明文。 UDP 没有 TLS 通道,network 为 UDP 时从不握手,未写端口且无 scheme 时取 80。
type HTTPClient ¶
type HTTPClient struct {
// contains filtered or unexported fields
}
HTTPClient 实例化 HTTP 客户端,持有按 (proxy, timeout, followRedirects) 键缓存的子客户端。
func DefaultHTTPClient ¶
func DefaultHTTPClient() *HTTPClient
DefaultHTTPClient 返回进程级默认 HTTP 客户端(用于 CEL 反连等无 Runner 上下文的场景)。
func (*HTTPClient) GetResource ¶
func (c *HTTPClient) GetResource(ctx context.Context, rawURL string, options OptionsRequest) (*http.Response, error)
GetResource 使用原始 URL 获取页面资源(图标),保留签名查询串的顺序和编码。 HTTP 客户端、连接池、代理与限速由当前实例管理,Cookie 会话来自 ctx。
资源请求按浏览器的方式跟随重定向,可以跨主机(图标常托管在 CDN),最多 maxRedirects 跳;离开请求的源之后不再携带自定义请求头。
func (*HTTPClient) ResourceCookies ¶
ResourceCookies 返回 ctx 会话中将发往 rawURL 的 Cookie 快照,供内容缓存隔离。
func (*HTTPClient) ResourceHash ¶
func (c *HTTPClient) ResourceHash(key [32]byte) (string, bool)
ResourceHash 读取当前客户端的资源哈希。键只保存摘要,不保留 URL、认证头或 Cookie。 资源内容受会话影响,因此缓存随客户端释放,不能跨 Engine 复用。
func (*HTTPClient) SendRawRequest ¶
func (c *HTTPClient) SendRawRequest(ctx context.Context, rawText, baseURL string, options OptionsRequest) (*http.Response, error)
SendRawRequest 使用原始 HTTP 编解码器,同时保持请求取消、代理和逐次限流。
func (*HTTPClient) SendRequestHttp ¶
func (c *HTTPClient) SendRequestHttp(ctx context.Context, method, urlStr, body string, options OptionsRequest) (*http.Response, error)
SendRequestHttp 按配置发送 HTTP 请求(支持重定向与 POST body 复用)。
func (*HTTPClient) SetDisableKeepAlives ¶
func (c *HTTPClient) SetDisableKeepAlives(disabled bool)
SetDisableKeepAlives 控制后续新建 Transport 是否禁用 Keep-Alive。 已缓存的 Transport 保持原行为。
func (*HTTPClient) SetGlobalRateLimiter ¶ added in v1.6.0
func (c *HTTPClient) SetGlobalRateLimiter(limiter *rate.Limiter)
SetGlobalRateLimiter 设置实例发出的全部请求共用的总速率限制;nil 表示不限制。
func (*HTTPClient) SetHTTPDebug ¶
func (c *HTTPClient) SetHTTPDebug(enabled bool)
SetHTTPDebug 启用 HTTP 原始报文 dump(仅 Debug 模式应开启)。
func (*HTTPClient) SetInsecureSkipVerify ¶
func (c *HTTPClient) SetInsecureSkipVerify(skip bool)
SetInsecureSkipVerify 更新 TLS 证书校验策略(仅影响后续新建的 Transport)。
func (*HTTPClient) SetRateLimiter ¶
func (c *HTTPClient) SetRateLimiter(limiter *HostRateLimiter)
func (*HTTPClient) StoreResourceHash ¶
func (c *HTTPClient) StoreResourceHash(key [32]byte, hash string)
StoreResourceHash 保存成功读取的资源哈希,最多保留 4096 条;失败不缓存。
func (*HTTPClient) WaitRequest ¶
func (c *HTTPClient) WaitRequest(ctx context.Context, target string) error
WaitRequest 在每次实际发出请求前调用:先等待总速率的名额,再等待目标主机的名额。
type HostRateLimiter ¶
type HostRateLimiter struct {
// contains filtered or unexported fields
}
HostRateLimiter per-host 令牌桶限流器集合。
用法:
limiter := NewHostRateLimiter(50, 100) // 50 QPS / burst 100
if err := limiter.Wait(ctx, "https://example.com"); err != nil { return err }
qps / burst 任一为非正值时 NewHostRateLimiter 返回 nil, Wait / Allow 对 nil 接收器是 no-op(始终返回放行)。
func NewHostRateLimiter ¶
func NewHostRateLimiter(qps float64, burst int) *HostRateLimiter
NewHostRateLimiter 创建 per-host 限流器。 qps <= 0 或 burst <= 0 时返回 nil(视为禁用)。
func (*HostRateLimiter) Allow ¶
func (h *HostRateLimiter) Allow(target string) bool
Allow 非阻塞判断 host 当前是否有可用令牌。
func (*HostRateLimiter) SetEnabled ¶
func (h *HostRateLimiter) SetEnabled(on bool)
SetEnabled 运行期临时切换启用状态。
func (*HostRateLimiter) SetPerPort ¶ added in v1.6.1
func (h *HostRateLimiter) SetPerPort(on bool)
SetPerPort 切换限速粒度:false(默认)按主机名或 IP,同一主机的所有端口共用 一个令牌桶;true 按“主机:端口”,每个端口各有一个令牌桶。
type OptionsRequest ¶
type OptionsRequest struct {
Proxy string
Timeout time.Duration
FollowRedirects bool
InsecureSkipVerify bool
CustomHeaders map[string]string
// Probe 表示这是确定目标是否为 HTTP 服务的入口请求:失败就是失败,不做兼容性回退。
Probe bool
}
OptionsRequest 请求配置参数。
type ProxyError ¶ added in v1.7.0
ProxyError 表示代理本身不可用(连不上、不是代理、要求认证),与目标无关: 换任何目标都会失败,调用方应当停止而不是逐个目标重试。
func (*ProxyError) Error ¶ added in v1.7.0
func (e *ProxyError) Error() string
func (*ProxyError) Unwrap ¶ added in v1.7.0
func (e *ProxyError) Unwrap() error
type Request ¶
type TcpOrUdpConfig ¶
type TcpOrUdpConfig struct {
VerifyTLS bool // 是否校验 TLS 证书;默认保留扫描兼容性。
Network string // 网络类型,TCP 或 UDP
MaxRetries int // 最大重试次数
ReadSize int // 读取数据的缓冲区大小
DialTimeout time.Duration // 连接超时时间
WriteTimeout time.Duration // 写入超时时间
ReadTimeout time.Duration // 单次接收的总时长上限
ReadIdle time.Duration // TCP 收到数据后等待后续数据的空闲时间;0 表示自适应
RetryDelay time.Duration // 重试延迟时间
ProxyURL string // 代理URL
ServerName string // TLS ServerName;为空时使用连接地址中的主机
}
TcpOrUdpConfig 配置结构体。是否进行 TLS 握手由连接地址决定(见 ParseEndpoint)。