network

package
v1.3.0 Latest Latest
Warning

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

Go to latest
Published: Nov 5, 2026 License: MIT Imports: 30 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

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。

每个目标 host 独立持有一个 *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

View Source
const (
	MaxDefaultBody int64 = 512 * 1024
	DefaultTimeout       = 10 * time.Second
	HttpPrefix           = "http://"
	HttpsPrefix          = "https://"
)

请求体与超时默认值。

View Source
const (
	DefaultNetwork      = "tcp"
	DefaultDialTimeout  = 5 * time.Second
	DefaultWriteTimeout = 5 * time.Second
	DefaultReadTimeout  = 5 * time.Second
	DefaultRetryDelay   = 2 * time.Second
	DefaultReadSize     = 2048
	DefaultMaxRetries   = 3
)

Variables

This section is empty.

Functions

func AssignVariableRaw

func AssignVariableRaw(find string, variableMap map[string]any) string

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 ParseRequest

func ParseRequest(oReq *http.Request) (*proto.Request, error)

ParseRequest 解析 HTTP 请求为 proto.Request。

func RawParse

func RawParse(nc *Client, data []byte, res []byte, variableMap map[string]any) error

func ReadResponseBody

func ReadResponseBody(resp *http.Response, limit int64) ([]byte, error)

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 Url2ProtoUrl

func Url2ProtoUrl(u *url.URL) *proto.UrlType

Url2ProtoUrl 将 net/url.URL 转为 proto.UrlType。

func ValidateProxyURL added in v1.3.0

func ValidateProxyURL(raw string) (*url.URL, error)

ValidateProxyURL 校验代理地址是否受支持,返回归一化后的 URL。空字符串视为直连(返回 nil, nil)。

Types

type Client

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

Client 客户端结构体

func NewClientContext

func NewClientContext(ctx context.Context, address string, conf TcpOrUdpConfig) (*Client, error)

NewClientContext 将连接、TLS 握手和读写统一绑定到调用方的生命周期。

func (*Client) Close

func (c *Client) Close() error

Close 关闭连接

func (*Client) Receive

func (c *Client) Receive() ([]byte, error)

Receive 接收数据

func (*Client) Send

func (c *Client) Send(data []byte) error

Send 发送数据

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 NewHTTPClient

func NewHTTPClient() *HTTPClient

NewHTTPClient 创建 HTTP 客户端实例。

func (*HTTPClient) CheckProtocol

func (c *HTTPClient) CheckProtocol(ctx context.Context, host, proxy string, timeout time.Duration) (string, error)

CheckProtocol 探测目标应使用的 http/https 前缀。 ctx 取消或 timeout 到期会中断探测;timeout <= 0 时使用 DefaultTimeout。

func (*HTTPClient) Close

func (c *HTTPClient) Close() error

Close 关闭所有缓存 Transport 的空闲连接并清空缓存。

func (*HTTPClient) GetResource

func (c *HTTPClient) GetResource(ctx context.Context, rawURL string, options OptionsRequest) (*http.Response, error)

GetResource 使用原始 URL 获取页面资源,保留签名查询串的顺序和编码。 HTTP 客户端、CookieJar、连接池、代理与限速仍由当前实例管理。

func (*HTTPClient) ResourceCookies

func (c *HTTPClient) ResourceCookies(rawURL string, options OptionsRequest) []*http.Cookie

ResourceCookies 返回资源请求所使用会话的 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) 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

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

func (h *HostRateLimiter) Stats() (cachedHosts int, qps float64, burst int)

Stats 返回当前缓存的 host limiter 数量及配置参数。

func (*HostRateLimiter) Wait

func (h *HostRateLimiter) Wait(ctx context.Context, target string) error

Wait 阻塞等待 host 的令牌可用,或 ctx 超时 / 取消。 当 limiter 为 nil 或被禁用时立即返回 nil(fast path)。

type OptionsRequest

type OptionsRequest struct {
	Proxy              string
	Timeout            time.Duration
	FollowRedirects    bool
	InsecureSkipVerify bool
	CustomHeaders      map[string]string
}

OptionsRequest 请求配置参数。

type Request

type Request struct {
	FullURL        string
	Method         string
	Path           string
	Data           string
	Headers        map[string]string
	UnsafeHeaders  client.Headers
	UnsafeRawBytes []byte
}

func Parse

func Parse(request, baseURL string, unsafe bool) (*Request, error)

Parse parses the raw request as supplied by the user

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 // 读取超时时间
	RetryDelay   time.Duration // 重试延迟时间
	ProxyURL     string        // 代理URL
	IsLts        bool          // 是否发送LTS请求
	ServerName   string        // ServerName对tls请求的配置
}

TcpOrUdpConfig 配置结构体

Jump to

Keyboard shortcuts

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