跳转到内容

std.http.Client

标准库Zig 0.17.1官方原文
源码std/http/Client.zig

第 1 行

HTTP(S) 客户端实现。

连接以线程安全方式打开,但单个 Request 并非线程安全。

可通过 std.options.http_disable_tls 禁用 TLS 支持。

字段

allocator: Allocator

用于所有客户端分配。必须线程安全。

io: Io

用于打开 TCP 连接。

ca_bundle_lock: if (disable_tls) void else Io.RwLock = if (disable_tls) {} else .init
ca_bundle: if (disable_tls) void else std.crypto.Certificate.Bundle = if (disable_tls) {} else .empty
tls_buffer_size: if (disable_tls) u0 else usize = if (disable_tls) 0 else std.crypto.tls.Client.min_buffer_len

同时用于读取器和写入器缓冲区。

ssl_key_log: ?*std.crypto.tls.Client.SslKeyLog = null

若非 null,则将 SSL 密钥记录到流中。创建此类流后, 其他能够访问此流的进程就可以解密通过此 Client 创建的连接上的全部流量。

now: ?Io.Timestamp = null

用于判定证书是否过期的时间。

若为 null,客户端下次发起 HTTPS 请求时, 会先检查时间并重新扫描系统根证书。

connection_pool: ConnectionPool = .{}

可复用连接的池(包含当前正在使用的连接)。

read_buffer_size: usize = 8192

每个 Connection 为读取缓冲区分配此大小。

如果全部 HTTP 标头无法容纳在这么多字节中, Request.wait 将返回 error.HttpHeadersOversize。

write_buffer_size: usize = 1024

每个 Connection 为写入器缓冲区分配这么多内存。

http_proxy: ?*Proxy = null

若已设置,全部 HTTP 流量都通过此第三方。 客户端有活动连接时,不得修改此字段。 指向外部拥有的内存的指针。

https_proxy: ?*Proxy = null

若填充此项,所有 https 流量均经由此第三方。 客户端存在活动连接时,不得修改此字段。 指针指向外部拥有的内存。

std.http.Client.Allocator

别名

第 17 行

别名目标 std.mem.Allocator

std.http.Client.assert

别名

第 18 行

别名目标 std.debug.assert

std.http.Client.basic_authorization

命名空间

第 1383 行

std.http.Client.basic_authorization.max_password_len

常量

第 1385 行

std.http.Client.basic_authorization.max_user_len

常量

第 1384 行

std.http.Client.basic_authorization.max_value_len

常量

第 1386 行

std.http.Client.basic_authorization.value

函数

第 1408 行

pub fn value(uri: Uri, out: []u8) []u8

参数

uri: Uri
out: []u8

std.http.Client.basic_authorization.valueLength

函数

第 1388 行

pub fn valueLength(user_len: usize, password_len: usize) usize

参数

user_len: usize
password_len: usize

std.http.Client.basic_authorization.valueLengthFromUri

函数

第 1392 行

pub fn valueLengthFromUri(uri: Uri) usize

参数

uri: Uri

std.http.Client.basic_authorization.write

函数

第 1414 行

pub fn write(uri: Uri, out: *Writer) Writer.Error!void

参数

uri: Uri
out: *Writer

错误

WriteFailed

详细诊断信息见 Writer 实现。

std.http.Client.builtin

常量

第 9 行

std.http.Client.Client

别名

第 7 行

别名目标 std.http.Client

std.http.Client.connect

函数

第 1607 行

使用指定协议连接到 host:port。若已有 打开的连接,则复用该连接。

若客户端配置了代理,则通过代理 连接主机。

此函数是线程安全的。

pub fn connect( client: *Client, host: HostName, port: u16, protocol: Protocol, ) ConnectError!*Connection

参数

client: *Client
host: HostName
port: u16
protocol: Protocol

错误

AccessDenied BindError

该地址受到保护,当前用户没有绑定它的权限。

AddressFamilyUnsupported BindError

该地址对于套接字的地址族无效。

AddressInUse BindError

地址已被占用。当绑定端口为 0, 但所有临时端口均已使用时,可能发生此情况。

AddressUnavailable BindError

请求了不存在的接口,或请求的地址不是本地地址。

Canceled Cancelable

调用方请求停止异步操作。

CertificateBundleLoadFailure RequestError
ConnectionPending ConnectError
ConnectionRefused ConnectError
ConnectionResetByPeer ConnectError
DetectingNetworkConfigurationFailed LookupError

无法打开或读取 "/etc/hosts" 或 "/etc/resolv.conf"。

HostUnreachable ConnectError
InvalidDnsAAAARecord LookupError
InvalidDnsARecord LookupError
InvalidDnsCnameRecord LookupError
InvalidHostName RequestError
NameServerFailure LookupError
NetworkDown BindError

用于到达目标的本地网络接口已离线。

NetworkUnreachable ConnectError
NoAddressReturned LookupError
OptionUnsupported BindError

Io 实现不支持某个 BindOptions。

OutOfMemory Error
ProcessFdQuotaExceeded BindError

已达到每进程可打开文件描述符数量上限。

ProtocolUnsupportedByAddressFamily BindError
ProtocolUnsupportedBySystem BindError
ResolvConfParseFailed LookupError
SocketModeUnsupported BindError
SystemFdQuotaExceeded BindError

已达到系统范围内已打开文件的总数上限。

SystemResources BindError

操作系统内部内存或其他资源不足。

Timeout ConnectError
TlsInitializationFailed ConnectTcpError
Unexpected UnexpectedError

操作系统返回了未记录在文档中的错误码。

理论上不可能出现此错误,但处理 此错误优于触发未定义行为。

观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。

UnknownHostName LookupError
UnsupportedUriScheme RequestError
UriMissingHost RequestError
WouldBlock ConnectError

已请求非阻塞模式,但该操作无法立即返回。

std.http.Client.ConnectError

错误集合

第 1598 行

错误

AccessDenied BindError

该地址受到保护,当前用户没有绑定它的权限。

AddressFamilyUnsupported BindError

该地址对于套接字的地址族无效。

AddressInUse BindError

地址已被占用。当绑定端口为 0, 但所有临时端口均已使用时,可能发生此情况。

AddressUnavailable BindError

请求了不存在的接口,或请求的地址不是本地地址。

Canceled Cancelable

调用方请求停止异步操作。

CertificateBundleLoadFailure RequestError
ConnectionPending ConnectError
ConnectionRefused ConnectError
ConnectionResetByPeer ConnectError
DetectingNetworkConfigurationFailed LookupError

无法打开或读取 "/etc/hosts" 或 "/etc/resolv.conf"。

HostUnreachable ConnectError
InvalidDnsAAAARecord LookupError
InvalidDnsARecord LookupError
InvalidDnsCnameRecord LookupError
InvalidHostName RequestError
NameServerFailure LookupError
NetworkDown BindError

用于到达目标的本地网络接口已离线。

NetworkUnreachable ConnectError
NoAddressReturned LookupError
OptionUnsupported BindError

Io 实现不支持某个 BindOptions。

OutOfMemory Error
ProcessFdQuotaExceeded BindError

已达到每进程可打开文件描述符数量上限。

ProtocolUnsupportedByAddressFamily BindError
ProtocolUnsupportedBySystem BindError
ResolvConfParseFailed LookupError
SocketModeUnsupported BindError
SystemFdQuotaExceeded BindError

已达到系统范围内已打开文件的总数上限。

SystemResources BindError

操作系统内部内存或其他资源不足。

Timeout ConnectError
TlsInitializationFailed ConnectTcpError
Unexpected UnexpectedError

操作系统返回了未记录在文档中的错误码。

理论上不可能出现此错误,但处理 此错误优于触发未定义行为。

观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。

UnknownHostName LookupError
UnsupportedUriScheme RequestError
UriMissingHost RequestError
WouldBlock ConnectError

已请求非阻塞模式,但该操作无法立即返回。

std.http.Client.Connection

容器

第 229 行

字段

client: *Client
stream_writer: Io.net.Stream.Writer
stream_reader: Io.net.Stream.Reader
pool_node: std.DoublyLinkedList.Node

ConnectionPool.used 或 ConnectionPool.free 中的条目。

port: u16
host_len: u8
proxied: bool
closing: bool
protocol: Protocol

std.http.Client.Connection.destroy

函数

第 420 行

若未调用 flush 或 end 就调用此方法,数据将 被丢弃而不发送。

pub fn destroy(c: *Connection, io: Io) void

参数

c: *Connection
io: Io

std.http.Client.Connection.end

函数

第 473 行

若连接为 TLS 连接,则发送 close_notify 警报。

刷新所有缓冲区。

pub fn end(c: *Connection) Writer.Error!void

参数

错误

WriteFailed

详细诊断信息见 Writer 实现。

std.http.Client.Connection.flush

函数

第 461 行

pub fn flush(c: *Connection) Writer.Error!void

参数

错误

WriteFailed

详细诊断信息见 Writer 实现。

std.http.Client.Connection.getReadError

函数

第 387 行

pub fn getReadError(c: *const Connection) ?ReadError

参数

c: *const Connection

std.http.Client.Connection.getStream

函数

第 400 行

fn getStream(c: *Connection) Io.net.Stream

参数

std.http.Client.Connection.host

函数

第 404 行

pub fn host(c: *Connection) HostName

参数

std.http.Client.Connection.Plain

容器

第 241 行

字段

connection: Connection

std.http.Client.Connection.Plain.allocLen

函数

第 284 行

fn allocLen(client: *Client, host_len: usize) usize

参数

client: *Client
host_len: usize

std.http.Client.Connection.Plain.create

函数

第 244 行

fn create( client: *Client, remote_host: HostName, port: u16, stream: Io.net.Stream, ) error{OutOfMemory}!*Plain

参数

client: *Client
remote_host: HostName
port: u16
stream: Io.net.Stream

错误

OutOfMemory

std.http.Client.Connection.Plain.destroy

函数

第 277 行

fn destroy(plain: *Plain) void

参数

plain: *Plain

std.http.Client.Connection.Plain.host

函数

第 288 行

fn host(plain: *Plain) HostName

参数

plain: *Plain

std.http.Client.Connection.reader

函数

第 450 行

从服务器到客户端的 HTTP 协议数据。 它直接来自 stream_reader,或来自 TLS 客户端。

pub fn reader(c: *Connection) *Reader

参数

std.http.Client.Connection.ReadError

错误集合

第 385 行

错误

AccessDenied Error

文件描述符不具有读取所需权限。

Canceled Cancelable

调用方请求停止异步操作。

ConnectionResetByPeer Error
ConnectionTimedOut Error

远端对等方未响应正在进行的通信,导致 操作系统中止连接。

NetworkDown Error
SocketUnconnected Error
SystemResources Error
TlsAlert ReadError

警报说明将存储在 alert 中。

TlsBadLength ReadError
TlsBadRecordMac ReadError
TlsConnectionTruncated ReadError
TlsDecodeError ReadError
TlsIllegalParameter ReadError
TlsRecordOverflow ReadError
TlsSequenceOverflow ReadError
TlsUnexpectedMessage ReadError
Unexpected UnexpectedError

操作系统返回了未记录在文档中的错误码。

理论上不可能出现此错误,但处理 此错误优于触发未定义行为。

观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。

std.http.Client.Connection.Tls

容器

第 294 行

字段

client: std.crypto.tls.Client
connection: Connection

std.http.Client.Connection.Tls.allocLen

函数

第 373 行

fn allocLen(client: *Client, host_len: usize) usize

参数

client: *Client
host_len: usize

std.http.Client.Connection.Tls.create

函数

第 299 行

断言 client.now 非空。

fn create( client: *Client, remote_host: HostName, port: u16, stream: Io.net.Stream, ) !*Tls

参数

client: *Client
remote_host: HostName
port: u16
stream: Io.net.Stream

std.http.Client.Connection.Tls.destroy

函数

第 366 行

fn destroy(tls: *Tls) void

参数

tls: *Tls

std.http.Client.Connection.Tls.host

函数

第 379 行

fn host(tls: *Tls) HostName

参数

tls: *Tls

std.http.Client.Connection.writer

函数

第 437 行

从客户端到服务器的 HTTP 协议数据。 它直接送往 stream_writer 或 TLS 客户端。

pub fn writer(c: *Connection) *Writer

参数

std.http.Client.ConnectionPool

容器

第 65 行

保存已打开连接以供复用的最近最少使用缓存。

字段

mutex: Io.Mutex = .init
used: std.DoublyLinkedList = .{}

当前正在使用的已打开连接。

free: std.DoublyLinkedList = .{}

当前未使用的已打开连接。

free_len: usize = 0
free_size: usize = 32

std.http.Client.ConnectionPool.acquire

函数

第 114 行

从连接池获取现有连接。此函数是线程安全的。

pub fn acquire(pool: *ConnectionPool, io: Io, connection: *Connection) Io.Cancelable!void

参数

pool: *ConnectionPool
io: Io
connection: *Connection

错误

Canceled

调用方请求停止异步操作。

std.http.Client.ConnectionPool.acquireUnsafe

函数

第 106 行

从连接池获取已有连接。此函数非线程安全。

pub fn acquireUnsafe(pool: *ConnectionPool, connection: *Connection) void

参数

pool: *ConnectionPool
connection: *Connection

std.http.Client.ConnectionPool.addUsed

函数

第 151 行

将新创建的节点加入已使用连接池。此函数线程安全。

pub fn addUsed(pool: *ConnectionPool, io: Io, connection: *Connection) Io.Cancelable!void

参数

pool: *ConnectionPool
io: Io
connection: *Connection

错误

Canceled

调用方请求停止异步操作。

std.http.Client.ConnectionPool.Criteria

容器

第 75 行

判定连接是否匹配的条件。

字段

host: HostName
port: u16
protocol: Protocol

std.http.Client.ConnectionPool.deinit

函数

第 182 行

释放连接池并关闭其中所有连接。

此后对连接池的所有操作都会死锁。

线程安全。

pub fn deinit(pool: *ConnectionPool, io: Io) void

参数

pool: *ConnectionPool
io: Io

std.http.Client.ConnectionPool.findConnection

函数

第 85 行

从连接池查找并获取符合条件的连接。 未找到连接时返回 null。

线程安全。

pub fn findConnection(pool: *ConnectionPool, io: Io, criteria: Criteria) Io.Cancelable!?*Connection

参数

pool: *ConnectionPool
io: Io
criteria: Criteria

错误

Canceled

调用方请求停止异步操作。

std.http.Client.ConnectionPool.release

函数

第 125 行

尝试将连接释放回连接池。 如果连接已标记为正在关闭,则改为关闭它。

线程安全。

pub fn release(pool: *ConnectionPool, connection: *Connection, io: Io) void

参数

pool: *ConnectionPool
connection: *Connection
io: Io

std.http.Client.ConnectionPool.resize

函数

第 163 行

调整连接池大小。

若新大小小于当前大小,则关闭空闲连接,直到连接池达到新大小。

线程安全。

pub fn resize(pool: *ConnectionPool, io: Io, new_size: usize) Io.Cancelable!void

参数

pool: *ConnectionPool
io: Io
new_size: usize

错误

Canceled

调用方请求停止异步操作。

std.http.Client.connectProxied

函数

第 1533 行

通过指定代理,使用 HTTP CONNECT 连接到 proxied_host:proxied_port。若已有打开的连接,则复用它。

此函数是线程安全的。

pub fn connectProxied( client: *Client, proxy: *Proxy, proxied_host: HostName, proxied_port: u16, ) !*Connection

参数

client: *Client
proxy: *Proxy
proxied_host: HostName
proxied_port: u16

std.http.Client.connectTcp

函数

第 1433 行

若已有匹配 host 和 port 的连接处于打开状态,则复用该 Connection。

线程安全。

pub fn connectTcp( client: *Client, host: HostName, port: u16, protocol: Protocol, ) ConnectTcpError!*Connection

参数

client: *Client
host: HostName
port: u16
protocol: Protocol

错误

AccessDenied BindError

该地址受到保护,当前用户没有绑定它的权限。

AddressFamilyUnsupported BindError

该地址对于套接字的地址族无效。

AddressInUse BindError

地址已被占用。当绑定端口为 0, 但所有临时端口均已使用时,可能发生此情况。

AddressUnavailable BindError

请求了不存在的接口,或请求的地址不是本地地址。

Canceled Cancelable

调用方请求停止异步操作。

ConnectionPending ConnectError
ConnectionRefused ConnectError
ConnectionResetByPeer ConnectError
DetectingNetworkConfigurationFailed LookupError

无法打开或读取 "/etc/hosts" 或 "/etc/resolv.conf"。

HostUnreachable ConnectError
InvalidDnsAAAARecord LookupError
InvalidDnsARecord LookupError
InvalidDnsCnameRecord LookupError
NameServerFailure LookupError
NetworkDown BindError

用于到达目标的本地网络接口已离线。

NetworkUnreachable ConnectError
NoAddressReturned LookupError
OptionUnsupported BindError

Io 实现不支持某个 BindOptions。

OutOfMemory Error
ProcessFdQuotaExceeded BindError

已达到每进程可打开文件描述符数量上限。

ProtocolUnsupportedByAddressFamily BindError
ProtocolUnsupportedBySystem BindError
ResolvConfParseFailed LookupError
SocketModeUnsupported BindError
SystemFdQuotaExceeded BindError

已达到系统范围内已打开文件的总数上限。

SystemResources BindError

操作系统内部内存或其他资源不足。

Timeout ConnectError
TlsInitializationFailed
Unexpected UnexpectedError

操作系统返回了未记录在文档中的错误码。

理论上不可能出现此错误,但处理 此错误优于触发未定义行为。

观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。

UnknownHostName LookupError
WouldBlock ConnectError

已请求非阻塞模式,但该操作无法立即返回。

std.http.Client.ConnectTcpError

错误集合

第 1426 行

错误

AccessDenied BindError

该地址受到保护,当前用户没有绑定它的权限。

AddressFamilyUnsupported BindError

该地址对于套接字的地址族无效。

AddressInUse BindError

地址已被占用。当绑定端口为 0, 但所有临时端口均已使用时,可能发生此情况。

AddressUnavailable BindError

请求了不存在的接口,或请求的地址不是本地地址。

Canceled Cancelable

调用方请求停止异步操作。

ConnectionPending ConnectError
ConnectionRefused ConnectError
ConnectionResetByPeer ConnectError
DetectingNetworkConfigurationFailed LookupError

无法打开或读取 "/etc/hosts" 或 "/etc/resolv.conf"。

HostUnreachable ConnectError
InvalidDnsAAAARecord LookupError
InvalidDnsARecord LookupError
InvalidDnsCnameRecord LookupError
NameServerFailure LookupError
NetworkDown BindError

用于到达目标的本地网络接口已离线。

NetworkUnreachable ConnectError
NoAddressReturned LookupError
OptionUnsupported BindError

Io 实现不支持某个 BindOptions。

OutOfMemory Error
ProcessFdQuotaExceeded BindError

已达到每进程可打开文件描述符数量上限。

ProtocolUnsupportedByAddressFamily BindError
ProtocolUnsupportedBySystem BindError
ResolvConfParseFailed LookupError
SocketModeUnsupported BindError
SystemFdQuotaExceeded BindError

已达到系统范围内已打开文件的总数上限。

SystemResources BindError

操作系统内部内存或其他资源不足。

Timeout ConnectError
TlsInitializationFailed
Unexpected UnexpectedError

操作系统返回了未记录在文档中的错误码。

理论上不可能出现此错误,但处理 此错误优于触发未定义行为。

观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。

UnknownHostName LookupError
WouldBlock ConnectError

已请求非阻塞模式,但该操作无法立即返回。

std.http.Client.connectTcpOptions

函数

第 1452 行

pub fn connectTcpOptions(client: *Client, options: ConnectTcpOptions) ConnectTcpError!*Connection

参数

client: *Client
options: ConnectTcpOptions

错误

AccessDenied BindError

该地址受到保护,当前用户没有绑定它的权限。

AddressFamilyUnsupported BindError

该地址对于套接字的地址族无效。

AddressInUse BindError

地址已被占用。当绑定端口为 0, 但所有临时端口均已使用时,可能发生此情况。

AddressUnavailable BindError

请求了不存在的接口,或请求的地址不是本地地址。

Canceled Cancelable

调用方请求停止异步操作。

ConnectionPending ConnectError
ConnectionRefused ConnectError
ConnectionResetByPeer ConnectError
DetectingNetworkConfigurationFailed LookupError

无法打开或读取 "/etc/hosts" 或 "/etc/resolv.conf"。

HostUnreachable ConnectError
InvalidDnsAAAARecord LookupError
InvalidDnsARecord LookupError
InvalidDnsCnameRecord LookupError
NameServerFailure LookupError
NetworkDown BindError

用于到达目标的本地网络接口已离线。

NetworkUnreachable ConnectError
NoAddressReturned LookupError
OptionUnsupported BindError

Io 实现不支持某个 BindOptions。

OutOfMemory Error
ProcessFdQuotaExceeded BindError

已达到每进程可打开文件描述符数量上限。

ProtocolUnsupportedByAddressFamily BindError
ProtocolUnsupportedBySystem BindError
ResolvConfParseFailed LookupError
SocketModeUnsupported BindError
SystemFdQuotaExceeded BindError

已达到系统范围内已打开文件的总数上限。

SystemResources BindError

操作系统内部内存或其他资源不足。

Timeout ConnectError
TlsInitializationFailed
Unexpected UnexpectedError

操作系统返回了未记录在文档中的错误码。

理论上不可能出现此错误,但处理 此错误优于触发未定义行为。

观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。

UnknownHostName LookupError
WouldBlock ConnectError

已请求非阻塞模式,但该操作无法立即返回。

std.http.Client.ConnectTcpOptions

容器

第 1442 行

字段

host: HostName
port: u16
protocol: Protocol
proxied_host: ?HostName = null
proxied_port: ?u16 = null
timeout: Io.Timeout = .none

std.http.Client.connectUnix

函数

第 1497 行

将 path 作为 Unix 域套接字连接。若已有打开连接,则复用它。

此函数线程安全。

pub fn connectUnix(client: *Client, path: []const u8) ConnectUnixError!*Connection

参数

client: *Client
path: []const u8

错误

Canceled Cancelable

调用方请求停止异步操作。

NameTooLong
OutOfMemory Error

std.http.Client.ConnectUnixError

错误集合

第 1492 行

错误

Canceled Cancelable

调用方请求停止异步操作。

NameTooLong
OutOfMemory Error

std.http.Client.createProxyFromEnvVar

函数

第 1350 行

fn createProxyFromEnvVar( arena: Allocator, environ_map: *const std.process.Environ.Map, env_var_names: []const []const u8, ) !?*Proxy

参数

arena: Allocator
environ_map: *const std.process.Environ.Map
env_var_names: []const []const u8

std.http.Client.deinit

函数

第 1314 行

释放与客户端关联的全部资源。

调用此函数前,必须反初始化所有待处理请求并释放所有活动连接。

pub fn deinit(client: *Client) void

参数

client: *Client

std.http.Client.disable_tls

常量

第 23 行

std.http.Client.fetch

函数

第 1815 行

使用给定选项执行一次性 HTTP 请求。

此函数是线程安全的。

pub fn fetch(client: *Client, options: FetchOptions) FetchError!FetchResult

参数

client: *Client
options: FetchOptions

错误

AccessDenied BindError

该地址受到保护,当前用户没有绑定它的权限。

AddressFamilyUnsupported BindError

该地址对于套接字的地址族无效。

AddressInUse BindError

地址已被占用。当绑定端口为 0, 但所有临时端口均已使用时,可能发生此情况。

AddressUnavailable BindError

请求了不存在的接口,或请求的地址不是本地地址。

Canceled Cancelable

调用方请求停止异步操作。

CertificateBundleLoadFailure RequestError
ConnectionPending ConnectError
ConnectionRefused ConnectError
ConnectionResetByPeer ConnectError
DetectingNetworkConfigurationFailed LookupError

无法打开或读取 "/etc/hosts" 或 "/etc/resolv.conf"。

HostUnreachable ConnectError
HttpChunkInvalid ReceiveHeadError
HttpChunkTruncated ReceiveHeadError
HttpConnectionClosing HeadError

客户端在关闭流之前未发送任何头部字节。 这发生在保活连接最终关闭时。

HttpContentEncodingUnsupported ReceiveHeadError
HttpHeadersInvalid ReceiveHeadError

服务器发送了不符合 HTTP 协议的标头。

若要获得更详细的诊断信息,可将 http.Reader.head_buffer 直接传给 Request.Head.parse。

HttpHeadersOversize HeadError

HTTP 头部字节数过多。

HTTP 规范建议在关闭连接前 响应状态码 431。

HttpRedirectLocationInvalid ReceiveHeadError
HttpRedirectLocationMissing ReceiveHeadError
HttpRedirectLocationOversize ReceiveHeadError
HttpRequestTruncated HeadError

收到部分 HTTP 请求,但在完整接收头部之前 连接已关闭。

InvalidDnsAAAARecord LookupError
InvalidDnsARecord LookupError
InvalidDnsCnameRecord LookupError
InvalidFormat ParseError
InvalidHostName ParseError
InvalidPort ParseError
NameServerFailure LookupError
NetworkDown BindError

用于到达目标的本地网络接口已离线。

NetworkUnreachable ConnectError
NoAddressReturned LookupError
OptionUnsupported BindError

Io 实现不支持某个 BindOptions。

OutOfMemory Error
ProcessFdQuotaExceeded BindError

已达到每进程可打开文件描述符数量上限。

ProtocolUnsupportedByAddressFamily BindError
ProtocolUnsupportedBySystem BindError
ReadFailed HeadError

读取 in 时出现传递性错误。

RedirectRequiresResend ReceiveHeadError

可在发送请求体之前调用 receiveHead, 以避免此情况。

ResolvConfParseFailed LookupError
SocketModeUnsupported BindError
StreamTooLong
SystemFdQuotaExceeded BindError

已达到系统范围内已打开文件的总数上限。

SystemResources BindError

操作系统内部内存或其他资源不足。

Timeout ConnectError
TlsInitializationFailed ConnectTcpError
TooManyHttpRedirects ReceiveHeadError
Unexpected UnexpectedError

操作系统返回了未记录在文档中的错误码。

理论上不可能出现此错误,但处理 此错误优于触发未定义行为。

观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。

UnexpectedCharacter ParseError
UnknownHostName LookupError
UnsupportedCompressionMethod
UnsupportedUriScheme RequestError
UriMissingHost RequestError
WouldBlock ConnectError

已请求非阻塞模式,但该操作无法立即返回。

WriteFailed ReceiveHeadError

发送请求失败。错误码可在 Connection 对象中获取。

std.http.Client.FetchError

错误集合

第 1805 行

错误

AccessDenied BindError

该地址受到保护,当前用户没有绑定它的权限。

AddressFamilyUnsupported BindError

该地址对于套接字的地址族无效。

AddressInUse BindError

地址已被占用。当绑定端口为 0, 但所有临时端口均已使用时,可能发生此情况。

AddressUnavailable BindError

请求了不存在的接口,或请求的地址不是本地地址。

Canceled Cancelable

调用方请求停止异步操作。

CertificateBundleLoadFailure RequestError
ConnectionPending ConnectError
ConnectionRefused ConnectError
ConnectionResetByPeer ConnectError
DetectingNetworkConfigurationFailed LookupError

无法打开或读取 "/etc/hosts" 或 "/etc/resolv.conf"。

HostUnreachable ConnectError
HttpChunkInvalid ReceiveHeadError
HttpChunkTruncated ReceiveHeadError
HttpConnectionClosing HeadError

客户端在关闭流之前未发送任何头部字节。 这发生在保活连接最终关闭时。

HttpContentEncodingUnsupported ReceiveHeadError
HttpHeadersInvalid ReceiveHeadError

服务器发送了不符合 HTTP 协议的标头。

若要获得更详细的诊断信息,可将 http.Reader.head_buffer 直接传给 Request.Head.parse。

HttpHeadersOversize HeadError

HTTP 头部字节数过多。

HTTP 规范建议在关闭连接前 响应状态码 431。

HttpRedirectLocationInvalid ReceiveHeadError
HttpRedirectLocationMissing ReceiveHeadError
HttpRedirectLocationOversize ReceiveHeadError
HttpRequestTruncated HeadError

收到部分 HTTP 请求,但在完整接收头部之前 连接已关闭。

InvalidDnsAAAARecord LookupError
InvalidDnsARecord LookupError
InvalidDnsCnameRecord LookupError
InvalidFormat ParseError
InvalidHostName ParseError
InvalidPort ParseError
NameServerFailure LookupError
NetworkDown BindError

用于到达目标的本地网络接口已离线。

NetworkUnreachable ConnectError
NoAddressReturned LookupError
OptionUnsupported BindError

Io 实现不支持某个 BindOptions。

OutOfMemory Error
ProcessFdQuotaExceeded BindError

已达到每进程可打开文件描述符数量上限。

ProtocolUnsupportedByAddressFamily BindError
ProtocolUnsupportedBySystem BindError
ReadFailed HeadError

读取 in 时出现传递性错误。

RedirectRequiresResend ReceiveHeadError

可在发送请求体之前调用 receiveHead, 以避免此情况。

ResolvConfParseFailed LookupError
SocketModeUnsupported BindError
StreamTooLong
SystemFdQuotaExceeded BindError

已达到系统范围内已打开文件的总数上限。

SystemResources BindError

操作系统内部内存或其他资源不足。

Timeout ConnectError
TlsInitializationFailed ConnectTcpError
TooManyHttpRedirects ReceiveHeadError
Unexpected UnexpectedError

操作系统返回了未记录在文档中的错误码。

理论上不可能出现此错误,但处理 此错误优于触发未定义行为。

观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。

UnexpectedCharacter ParseError
UnknownHostName LookupError
UnsupportedCompressionMethod
UnsupportedUriScheme RequestError
UriMissingHost RequestError
WouldBlock ConnectError

已请求非阻塞模式,但该操作无法立即返回。

WriteFailed ReceiveHeadError

发送请求失败。错误码可在 Connection 对象中获取。

std.http.Client.FetchOptions

容器

第 1768 行

字段

redirect_buffer: ?[]u8 = null

null 表示将在堆上分配。RFC 9110 建议至少使用 8000 字节。

decompress_buffer: ?[]u8 = null

null 表示将在堆上分配。

redirect_behavior: ?Request.RedirectBehavior = null
response_writer: ?*Writer = null

如果服务器发送消息体,则将其写入此处。

location: Location
method: ?http.Method = null
payload: ?[]const u8 = null
raw_uri: bool = false
keep_alive: bool = true
headers: Request.Headers = .{}

具有默认行为且允许覆盖该行为的标准头字段。

extra_headers: []const http.Header = &.{}

即使跟随重定向至其他域名,也会保留 这些头部。 所有权属于外部;必须比 Request 存活更久。

privileged_headers: []const http.Header = &.{}

跟随重定向到其他域时会移除这些头字段。 所有权属于外部;生存期必须长于 Request。

std.http.Client.FetchOptions.Location

容器

第 1795 行

字段

url: []const u8
uri: Uri

std.http.Client.FetchResult

容器

第 1801 行

字段

status: http.Status

std.http.Client.HostName

别名

第 21 行

别名目标 std.Io.net.HostName

std.http.Client.http

别名

第 14 行

别名目标 std.http

std.http.Client.initDefaultProxies

函数

第 1328 行

通过标准代理环境变量填充 http_proxy 和 https_proxy。 断言客户端没有活动连接。 使用 arena 进行少量小型分配;这些分配的生存期必须长于客户端, 或至少持续到这些字段被设置为其他值。

pub fn initDefaultProxies(client: *Client, arena: Allocator, environ_map: *const std.process.Environ.Map) !void

参数

client: *Client
arena: Allocator
environ_map: *const std.process.Environ.Map

std.http.Client.Io

别名

第 12 行

别名目标 std.Io

std.http.Client.mem

别名

第 15 行

别名目标 std.mem

std.http.Client.Protocol

容器

第 203 行

字段

plain
tls

std.http.Client.Protocol.fromScheme

函数

第 214 行

pub fn fromScheme(scheme: []const u8) ?Protocol

参数

scheme: []const u8

std.http.Client.Protocol.fromUri

函数

第 224 行

pub fn fromUri(uri: Uri) ?Protocol

参数

uri: Uri

std.http.Client.Protocol.port

函数

第 207 行

fn port(protocol: Protocol) u16

参数

protocol: Protocol

std.http.Client.Proxy

容器

第 1302 行

字段

protocol: Protocol
host: HostName
authorization: ?[]const u8
port: u16
supports_connect: bool

std.http.Client.Reader

别名

第 20 行

别名目标 std.Io.Reader

std.http.Client.request

函数

第 1691 行

打开到 uri 指定主机的连接,并准备发送 HTTP 请求。

调用者负责对 Request 调用 deinit()。 此函数是线程安全的。

断言任何头字段的名称或值中都不含 "\r\n"。

pub fn request( client: *Client, method: http.Method, uri: Uri, options: RequestOptions, ) RequestError!Request

参数

client: *Client
method: http.Method
uri: Uri
options: RequestOptions

错误

AccessDenied BindError

该地址受到保护,当前用户没有绑定它的权限。

AddressFamilyUnsupported BindError

该地址对于套接字的地址族无效。

AddressInUse BindError

地址已被占用。当绑定端口为 0, 但所有临时端口均已使用时,可能发生此情况。

AddressUnavailable BindError

请求了不存在的接口,或请求的地址不是本地地址。

Canceled Cancelable

调用方请求停止异步操作。

CertificateBundleLoadFailure
ConnectionPending ConnectError
ConnectionRefused ConnectError
ConnectionResetByPeer ConnectError
DetectingNetworkConfigurationFailed LookupError

无法打开或读取 "/etc/hosts" 或 "/etc/resolv.conf"。

HostUnreachable ConnectError
InvalidDnsAAAARecord LookupError
InvalidDnsARecord LookupError
InvalidDnsCnameRecord LookupError
InvalidHostName
NameServerFailure LookupError
NetworkDown BindError

用于到达目标的本地网络接口已离线。

NetworkUnreachable ConnectError
NoAddressReturned LookupError
OptionUnsupported BindError

Io 实现不支持某个 BindOptions。

OutOfMemory Error
ProcessFdQuotaExceeded BindError

已达到每进程可打开文件描述符数量上限。

ProtocolUnsupportedByAddressFamily BindError
ProtocolUnsupportedBySystem BindError
ResolvConfParseFailed LookupError
SocketModeUnsupported BindError
SystemFdQuotaExceeded BindError

已达到系统范围内已打开文件的总数上限。

SystemResources BindError

操作系统内部内存或其他资源不足。

Timeout ConnectError
TlsInitializationFailed ConnectTcpError
Unexpected UnexpectedError

操作系统返回了未记录在文档中的错误码。

理论上不可能出现此错误,但处理 此错误优于触发未定义行为。

观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。

UnknownHostName LookupError
UnsupportedUriScheme
UriMissingHost
WouldBlock ConnectError

已请求非阻塞模式,但该操作无法立即返回。

std.http.Client.Request

容器

第 784 行

字段

uri: Uri

提供此字段,使客户端能够观察重定向后的 URI。

其底层内存在创建请求时由 API 用户 外部提供,之后又通过 redirect_buffer 外部提供给 receiveHead。

client: *Client
connection: ?*Connection

连接释放时此值为 null。

reader: http.Reader
keep_alive: bool
method: http.Method
version: http.Version = .@"HTTP/1.1"
transfer_encoding: TransferEncoding
redirect_behavior: RedirectBehavior
accept_encoding: @TypeOf(default_accept_encoding) = default_accept_encoding
handle_continue: bool

请求是否应在发送请求体之前处理 100-continue 响应。

headers: Headers

具有默认行为且允许覆盖该行为的标准头字段。

response_content_length: ?u64 = null

在 receiveHead 中赋值;在 deinit 中用于判断是否需要 丢弃响应体以复用连接。

response_transfer_encoding: http.TransferEncoding = .none

在 receiveHead 中赋值;在 deinit 中用于判断是否需要 丢弃响应体以复用连接。

payload_pending: bool = false

在 deinit 中用于判断请求体是否已经发送,从而确定 连接是否可以安全复用。

extra_headers: []const http.Header

即使跟随重定向至其他域名,也会保留 这些头部。 所有权属于外部;必须比 Request 存活更久。

privileged_headers: []const http.Header

跟随重定向到其他域时会移除这些头字段。 所有权属于外部;生存期必须长于 Request。

std.http.Client.Request.default_accept_encoding

常量

第 829 行

[@typeInfo(http.ContentEncoding).@"enum".field_names.len]bool

std.http.Client.Request.deinit

函数

第 888 行

将请求的 Connection 归还至 Client 的连接池。

pub fn deinit(r: *Request) void

参数

r: *Request

std.http.Client.Request.emitOverridableHeader

函数

第 1289 行

若需要默认行为则返回 true,否则处理 头部的写入(或不写入)。

fn emitOverridableHeader(prefix: []const u8, v: Headers.Value, bw: *Writer) Writer.Error!bool

参数

prefix: []const u8
v: Headers.Value
bw: *Writer

错误

WriteFailed

详细诊断信息见 Writer 实现。

std.http.Client.Request.Headers

容器

第 843 行

字段

host: Value = .default
authorization: Value = .default
user_agent: Value = .default
connection: Value = .default
accept_encoding: Value = .default
content_type: Value = .default

std.http.Client.Request.Headers.Value

容器

第 851 行

字段

default
omit
override: []const u8

std.http.Client.Request.receiveHead

函数

第 1134 行

如果处理重定向且请求没有载荷,此函数会自动跟随重定向。

若存在请求载荷,则返回 error.RedirectRequiresResend。

此函数接受辅助缓冲区,用于存储可能需要与先前 URI 合并、且大小任意的 URI。这些数据必须跨连接保持有效;输入缓冲区则位于连接中。

redirect_buffer 的生存期必须覆盖对 Request.uri 的访问。若将超出缓冲区容量,则改为返回 error.HttpRedirectLocationOversize。若不处理重定向,此缓冲区可以为空。RFC 9110 建议其大小至少为 8000 字节。

若此操作以 error.ReadFailed 失败,可调用 r.connection 的 Connection.getReadError 方法获取详细信息。

pub fn receiveHead(r: *Request, redirect_buffer: []u8) ReceiveHeadError!Response

参数

r: *Request
redirect_buffer: []u8

错误

AccessDenied BindError

该地址受到保护,当前用户没有绑定它的权限。

AddressFamilyUnsupported BindError

该地址对于套接字的地址族无效。

AddressInUse BindError

地址已被占用。当绑定端口为 0, 但所有临时端口均已使用时,可能发生此情况。

AddressUnavailable BindError

请求了不存在的接口,或请求的地址不是本地地址。

Canceled Cancelable

调用方请求停止异步操作。

CertificateBundleLoadFailure RequestError
ConnectionPending ConnectError
ConnectionRefused ConnectError
ConnectionResetByPeer ConnectError
DetectingNetworkConfigurationFailed LookupError

无法打开或读取 "/etc/hosts" 或 "/etc/resolv.conf"。

HostUnreachable ConnectError
HttpChunkInvalid
HttpChunkTruncated
HttpConnectionClosing HeadError

客户端在关闭流之前未发送任何头部字节。 这发生在保活连接最终关闭时。

HttpContentEncodingUnsupported
HttpHeadersInvalid

服务器发送了不符合 HTTP 协议的标头。

若要获得更详细的诊断信息,可将 http.Reader.head_buffer 直接传给 Request.Head.parse。

HttpHeadersOversize HeadError

HTTP 头部字节数过多。

HTTP 规范建议在关闭连接前 响应状态码 431。

HttpRedirectLocationInvalid
HttpRedirectLocationMissing
HttpRedirectLocationOversize
HttpRequestTruncated HeadError

收到部分 HTTP 请求,但在完整接收头部之前 连接已关闭。

InvalidDnsAAAARecord LookupError
InvalidDnsARecord LookupError
InvalidDnsCnameRecord LookupError
InvalidHostName RequestError
NameServerFailure LookupError
NetworkDown BindError

用于到达目标的本地网络接口已离线。

NetworkUnreachable ConnectError
NoAddressReturned LookupError
OptionUnsupported BindError

Io 实现不支持某个 BindOptions。

OutOfMemory Error
ProcessFdQuotaExceeded BindError

已达到每进程可打开文件描述符数量上限。

ProtocolUnsupportedByAddressFamily BindError
ProtocolUnsupportedBySystem BindError
ReadFailed HeadError

读取 in 时出现传递性错误。

RedirectRequiresResend

可在发送请求体之前调用 receiveHead, 以避免此情况。

ResolvConfParseFailed LookupError
SocketModeUnsupported BindError
SystemFdQuotaExceeded BindError

已达到系统范围内已打开文件的总数上限。

SystemResources BindError

操作系统内部内存或其他资源不足。

Timeout ConnectError
TlsInitializationFailed ConnectTcpError
TooManyHttpRedirects
Unexpected UnexpectedError

操作系统返回了未记录在文档中的错误码。

理论上不可能出现此错误,但处理 此错误优于触发未定义行为。

观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。

UnknownHostName LookupError
UnsupportedUriScheme RequestError
UriMissingHost RequestError
WouldBlock ConnectError

已请求非阻塞模式,但该操作无法立即返回。

WriteFailed

发送请求失败。错误码可在 Connection 对象中获取。

std.http.Client.Request.ReceiveHeadError

错误集合

第 1092 行

错误

AccessDenied BindError

该地址受到保护,当前用户没有绑定它的权限。

AddressFamilyUnsupported BindError

该地址对于套接字的地址族无效。

AddressInUse BindError

地址已被占用。当绑定端口为 0, 但所有临时端口均已使用时,可能发生此情况。

AddressUnavailable BindError

请求了不存在的接口,或请求的地址不是本地地址。

Canceled Cancelable

调用方请求停止异步操作。

CertificateBundleLoadFailure RequestError
ConnectionPending ConnectError
ConnectionRefused ConnectError
ConnectionResetByPeer ConnectError
DetectingNetworkConfigurationFailed LookupError

无法打开或读取 "/etc/hosts" 或 "/etc/resolv.conf"。

HostUnreachable ConnectError
HttpChunkInvalid
HttpChunkTruncated
HttpConnectionClosing HeadError

客户端在关闭流之前未发送任何头部字节。 这发生在保活连接最终关闭时。

HttpContentEncodingUnsupported
HttpHeadersInvalid

服务器发送了不符合 HTTP 协议的标头。

若要获得更详细的诊断信息,可将 http.Reader.head_buffer 直接传给 Request.Head.parse。

HttpHeadersOversize HeadError

HTTP 头部字节数过多。

HTTP 规范建议在关闭连接前 响应状态码 431。

HttpRedirectLocationInvalid
HttpRedirectLocationMissing
HttpRedirectLocationOversize
HttpRequestTruncated HeadError

收到部分 HTTP 请求,但在完整接收头部之前 连接已关闭。

InvalidDnsAAAARecord LookupError
InvalidDnsARecord LookupError
InvalidDnsCnameRecord LookupError
InvalidHostName RequestError
NameServerFailure LookupError
NetworkDown BindError

用于到达目标的本地网络接口已离线。

NetworkUnreachable ConnectError
NoAddressReturned LookupError
OptionUnsupported BindError

Io 实现不支持某个 BindOptions。

OutOfMemory Error
ProcessFdQuotaExceeded BindError

已达到每进程可打开文件描述符数量上限。

ProtocolUnsupportedByAddressFamily BindError
ProtocolUnsupportedBySystem BindError
ReadFailed HeadError

读取 in 时出现传递性错误。

RedirectRequiresResend

可在发送请求体之前调用 receiveHead, 以避免此情况。

ResolvConfParseFailed LookupError
SocketModeUnsupported BindError
SystemFdQuotaExceeded BindError

已达到系统范围内已打开文件的总数上限。

SystemResources BindError

操作系统内部内存或其他资源不足。

Timeout ConnectError
TlsInitializationFailed ConnectTcpError
TooManyHttpRedirects
Unexpected UnexpectedError

操作系统返回了未记录在文档中的错误码。

理论上不可能出现此错误,但处理 此错误优于触发未定义行为。

观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。

UnknownHostName LookupError
UnsupportedUriScheme RequestError
UriMissingHost RequestError
WouldBlock ConnectError

已请求非阻塞模式,但该操作无法立即返回。

WriteFailed

发送请求失败。错误码可在 Connection 对象中获取。

std.http.Client.Request.redirect

函数

第 1212 行

此函数接受辅助缓冲区,用于存储任意长度的 URI。该 URI 可能需要与前一个 URI 合并,且其数据必须跨不同连接存活,而输入缓冲区位于连接内部。

aux_buf 的生命周期必须覆盖对 Request.uri 的全部访问。

fn redirect(r: *Request, head: *const Response.Head, aux_buf: *[]u8) !void

参数

r: *Request
head: *const Response.Head
aux_buf: *[]u8

std.http.Client.Request.RedirectBehavior

容器

第 860 行

除 not_allowed 或 unhandled 以外的任何值,表示仍允许的重定向次数。

字段

not_allowed = 0

下一次重定向将导致错误。

unhandled = std.math.maxInt(u16)

将重定向交给客户端,以直接分析重定向响应。

_

std.http.Client.Request.RedirectBehavior.init

函数

第 868 行

pub fn init(n: u16) RedirectBehavior

参数

n: u16

std.http.Client.Request.RedirectBehavior.remaining

函数

第 881 行

pub fn remaining(rb: RedirectBehavior) u16

参数

std.http.Client.Request.RedirectBehavior.subtractOne

函数

第 873 行

pub fn subtractOne(rb: *RedirectBehavior) void

参数

std.http.Client.Request.sendBodiless

函数

第 911 行

发送并刷新一个仅含 HTTP 头部、无消息体的完整请求。

pub fn sendBodiless(r: *Request) Writer.Error!void

参数

r: *Request

错误

WriteFailed

详细诊断信息见 Writer 实现。

std.http.Client.Request.sendBodilessUnflushed

函数

第 917 行

发送完整请求但不刷新,仅包含 HTTP 头部,不包含消息体。

pub fn sendBodilessUnflushed(r: *Request) Writer.Error!void

参数

r: *Request

错误

WriteFailed

详细诊断信息见 Writer 实现。

std.http.Client.Request.sendBody

函数

第 926 行

通过连接传输 HTTP 头部并刷新。

另见:

  • sendBodyUnflushed
pub fn sendBody(r: *Request, buffer: []u8) Writer.Error!http.BodyWriter

参数

r: *Request
buffer: []u8

错误

WriteFailed

详细诊断信息见 Writer 实现。

std.http.Client.Request.sendBodyComplete

函数

第 933 行

通过连接传输 HTTP 头部和消息体,并刷新。

pub fn sendBodyComplete(r: *Request, body: []u8) Writer.Error!void

参数

r: *Request
body: []u8

错误

WriteFailed

详细诊断信息见 Writer 实现。

std.http.Client.Request.sendBodyUnflushed

函数

第 946 行

通过连接传输 HTTP 头部;在调用 BodyWriter.flush 或 BodyWriter.end 前不会刷新。

另见:

  • sendBody
pub fn sendBodyUnflushed(r: *Request, buffer: []u8) Writer.Error!http.BodyWriter

参数

r: *Request
buffer: []u8

错误

WriteFailed

详细诊断信息见 Writer 实现。

std.http.Client.Request.sendHead

函数

第 991 行

发送 HTTP 头但不刷新。

fn sendHead(r: *Request) Writer.Error!void

参数

r: *Request

错误

WriteFailed

详细诊断信息见 Writer 实现。

std.http.Client.Request.TransferEncoding

容器

第 837 行

字段

content_length: u64
chunked: void
none: void

std.http.Client.RequestError

错误集合

第 1636 行

错误

AccessDenied BindError

该地址受到保护,当前用户没有绑定它的权限。

AddressFamilyUnsupported BindError

该地址对于套接字的地址族无效。

AddressInUse BindError

地址已被占用。当绑定端口为 0, 但所有临时端口均已使用时,可能发生此情况。

AddressUnavailable BindError

请求了不存在的接口,或请求的地址不是本地地址。

Canceled Cancelable

调用方请求停止异步操作。

CertificateBundleLoadFailure
ConnectionPending ConnectError
ConnectionRefused ConnectError
ConnectionResetByPeer ConnectError
DetectingNetworkConfigurationFailed LookupError

无法打开或读取 "/etc/hosts" 或 "/etc/resolv.conf"。

HostUnreachable ConnectError
InvalidDnsAAAARecord LookupError
InvalidDnsARecord LookupError
InvalidDnsCnameRecord LookupError
InvalidHostName
NameServerFailure LookupError
NetworkDown BindError

用于到达目标的本地网络接口已离线。

NetworkUnreachable ConnectError
NoAddressReturned LookupError
OptionUnsupported BindError

Io 实现不支持某个 BindOptions。

OutOfMemory Error
ProcessFdQuotaExceeded BindError

已达到每进程可打开文件描述符数量上限。

ProtocolUnsupportedByAddressFamily BindError
ProtocolUnsupportedBySystem BindError
ResolvConfParseFailed LookupError
SocketModeUnsupported BindError
SystemFdQuotaExceeded BindError

已达到系统范围内已打开文件的总数上限。

SystemResources BindError

操作系统内部内存或其他资源不足。

Timeout ConnectError
TlsInitializationFailed ConnectTcpError
Unexpected UnexpectedError

操作系统返回了未记录在文档中的错误码。

理论上不可能出现此错误,但处理 此错误优于触发未定义行为。

观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。

UnknownHostName LookupError
UnsupportedUriScheme
UriMissingHost
WouldBlock ConnectError

已请求非阻塞模式,但该操作无法立即返回。

std.http.Client.RequestOptions

容器

第 1643 行

字段

version: http.Version = .@"HTTP/1.1"
handle_continue: bool = true

自动忽略 100 Continue 响应。假定调用者不关心该响应,会在等待响应之前发送请求体。

若并非如此,且已知服务器会发送 100 Continue,则将此选项设为 false,在发送请求体之前等待响应。 若选择等待,但服务器在请求完成之前不发送 100 Continue,则该请求必然死锁。

keep_alive: bool = true

若为 false,则在这一次请求后关闭连接;若为 true, 则加入客户端连接池。

redirect_behavior: Request.RedirectBehavior = @fromBackingInt(@intCast(3))

此字段指定是否自动跟随重定向, 以及在返回错误之前最多跟随多少次重定向。

仅对可重复的请求跟随重定向,即没有 负载,或服务器已确认负载的请求。

connection: ?*Connection = null

必须是已获取的连接。

headers: Request.Headers = .{}

具有默认行为且允许覆盖该行为的标准头字段。

extra_headers: []const http.Header = &.{}

即使跟随重定向至其他域名,也会保留 这些头部。 所有权属于外部;必须比 Request 存活更久。

privileged_headers: []const http.Header = &.{}

跟随重定向到其他域时会移除这些头字段。 所有权属于外部;生存期必须长于 Request。

std.http.Client.Response

容器

第 483 行

字段

request: *Request
head: Head

初始化响应消息体流时,此结构中的指针 将失效。

std.http.Client.Response.bodyErr

函数

第 769 行

从 reader 或 readerDecompressing 返回的 Reader 收到 error.ReadFailed 后,使用此函数 访问更具体的错误码。

pub fn bodyErr(response: *const Response) ?http.Reader.BodyError

参数

response: *const Response

std.http.Client.Response.Head

容器

第 489 行

字段

bytes: []const u8
version: http.Version
status: http.Status
reason: []const u8
location: ?[]const u8 = null
content_type: ?[]const u8 = null
content_disposition: ?[]const u8 = null
keep_alive: bool
content_length: ?u64 = null

若存在,则为响应消息体的字节数。

transfer_encoding: http.TransferEncoding = .none
content_encoding: http.ContentEncoding = .identity

std.http.Client.Response.Head.int64

函数

第 693 行

inline fn int64(array: *const [8]u8) u64

参数

array: *const [8]u8

std.http.Client.Response.Head.invalidateStrings

函数

第 713 行

当 Head 的字符串内存失效时调用此函数, 帮助程序员避免缺陷。

fn invalidateStrings(h: *Head) void

参数

h: *Head

std.http.Client.Response.Head.iterateHeaders

函数

第 639 行

pub fn iterateHeaders(h: Head) http.HeaderIterator

参数

h: Head

用法示例

test iterateHeaders {
    const response_bytes = "HTTP/1.1 200 OK\r\n" ++
        "LOcation:url\r\n" ++
        "content-tYpe: text/plain\r\n" ++
        "content-disposition:attachment; filename=example.txt \r\n" ++
        "content-Length:10\r\n" ++
        "TRansfer-encoding:\tdeflate, chunked \r\n" ++
        "connectioN:\t keep-alive \r\n\r\n";

    const head = try Head.parse(response_bytes);
    var it = head.iterateHeaders();
    {
        const header = it.next().?;
        try testing.expectEqualStrings("LOcation", header.name);
        try testing.expectEqualStrings("url", header.value);
        try testing.expect(!it.is_trailer);
    }
    {
        const header = it.next().?;
        try testing.expectEqualStrings("content-tYpe", header.name);
        try testing.expectEqualStrings("text/plain", header.value);
        try testing.expect(!it.is_trailer);
    }
    {
        const header = it.next().?;
        try testing.expectEqualStrings("content-disposition", header.name);
        try testing.expectEqualStrings("attachment; filename=example.txt", header.value);
        try testing.expect(!it.is_trailer);
    }
    {
        const header = it.next().?;
        try testing.expectEqualStrings("content-Length", header.name);
        try testing.expectEqualStrings("10", header.value);
        try testing.expect(!it.is_trailer);
    }
    {
        const header = it.next().?;
        try testing.expectEqualStrings("TRansfer-encoding", header.name);
        try testing.expectEqualStrings("deflate, chunked", header.value);
        try testing.expect(!it.is_trailer);
    }
    {
        const header = it.next().?;
        try testing.expectEqualStrings("connectioN", header.name);
        try testing.expectEqualStrings("keep-alive", header.value);
        try testing.expect(!it.is_trailer);
    }
    try testing.expectEqual(null, it.next());
}

std.http.Client.Response.Head.parse

函数

第 515 行

pub fn parse(bytes: []const u8) ParseError!Head

参数

bytes: []const u8

错误

HttpConnectionHeaderUnsupported
HttpContentEncodingUnsupported
HttpHeaderContinuationsUnsupported
HttpHeadersInvalid
HttpTransferEncodingUnsupported
InvalidContentLength

用法示例

test parse {
    const response_bytes = "HTTP/1.1 200 OK\r\n" ++
        "LOcation:url\r\n" ++
        "content-tYpe: text/plain\r\n" ++
        "content-disposition:attachment; filename=example.txt \r\n" ++
        "content-Length:10\r\n" ++
        "TRansfer-encoding:\tdeflate, chunked \r\n" ++
        "connectioN:\t keep-alive \r\n\r\n";

    const head = try Head.parse(response_bytes);

    try testing.expectEqual(.@"HTTP/1.1", head.version);
    try testing.expectEqualStrings("OK", head.reason);
    try testing.expectEqual(.ok, head.status);

    try testing.expectEqualStrings("url", head.location.?);
    try testing.expectEqualStrings("text/plain", head.content_type.?);
    try testing.expectEqualStrings("attachment; filename=example.txt", head.content_disposition.?);

    try testing.expectEqual(true, head.keep_alive);
    try testing.expectEqual(10, head.content_length.?);
    try testing.expectEqual(.chunked, head.transfer_encoding);
    try testing.expectEqual(.deflate, head.content_encoding);
}

std.http.Client.Response.Head.ParseError

错误集合

第 506 行

错误

HttpConnectionHeaderUnsupported
HttpContentEncodingUnsupported
HttpHeaderContinuationsUnsupported
HttpHeadersInvalid
HttpTransferEncodingUnsupported
InvalidContentLength

std.http.Client.Response.Head.parseInt3

函数

第 697 行

fn parseInt3(text: *const [3]u8) u10

参数

text: *const [3]u8

用法示例

test parseInt3 {
    const expectEqual = testing.expectEqual;
    try expectEqual(@as(u10, 0), parseInt3("000"));
    try expectEqual(@as(u10, 418), parseInt3("418"));
    try expectEqual(@as(u10, 999), parseInt3("999"));
}

std.http.Client.Response.iterateTrailers

函数

第 773 行

pub fn iterateTrailers(response: *const Response) http.HeaderIterator

参数

response: *const Response

std.http.Client.Response.reader

函数

第 731 行

如果已协商正文压缩,则返回压缩字节。

如果返回的 Reader 返回 error.ReadFailed, 可通过 bodyErr 取得具体错误。

断言此函数仅调用一次。

另请参见:

  • readerDecompressing
pub fn reader(response: *Response, transfer_buffer: []u8) *Reader

参数

response: *Response
transfer_buffer: []u8

std.http.Client.Response.readerDecompressing

函数

第 748 行

若已协商使用压缩消息体,则返回解压后的字节。

若返回的 Reader 返回 error.ReadFailed,可通过 bodyErr 获取错误。

断言此函数仅调用一次。

另见:

  • reader
pub fn readerDecompressing( response: *Response, transfer_buffer: []u8, decompress: *http.Decompress, decompress_buffer: []u8, ) *Reader

参数

response: *Response
transfer_buffer: []u8
decompress: *http.Decompress
decompress_buffer: []u8

std.http.Client.std

别名

第 11 行

别名目标 std

std.http.Client.testing

别名

第 13 行

别名目标 std.testing

std.http.Client.Uri

别名

第 16 行

别名目标 std.Uri

std.http.Client.uriPort

函数

第 1681 行

fn uriPort(uri: Uri, protocol: Protocol) u16

参数

uri: Uri
protocol: Protocol

std.http.Client.Writer

别名

第 19 行

别名目标 std.Io.Writer

源码

std/http/Client.zig

//! HTTP(S) 客户端实现。
//!
//! 连接以线程安全方式打开,但单个 Request 并非线程安全。
//!
//! 可通过 `std.options.http_disable_tls` 禁用 TLS 支持。
//!
const Client = @This();

const builtin = @import("builtin");

const std = @import("../std.zig");
const Io = std.Io;
const testing = std.testing;
const http = std.http;
const mem = std.mem;
const Uri = std.Uri;
const Allocator = std.mem.Allocator;
const assert = std.debug.assert;
const Writer = std.Io.Writer;
const Reader = std.Io.Reader;
const HostName = std.Io.net.HostName;

pub const disable_tls = std.options.http_disable_tls;

/// 用于所有客户端分配。必须线程安全。
allocator: Allocator,
/// 用于打开 TCP 连接。
io: Io,

ca_bundle_lock: if (disable_tls) void else Io.RwLock = if (disable_tls) {} else .init,
ca_bundle: if (disable_tls) void else std.crypto.Certificate.Bundle = if (disable_tls) {} else .empty,
/// 同时用于读取器和写入器缓冲区。
tls_buffer_size: if (disable_tls) u0 else usize = if (disable_tls) 0 else std.crypto.tls.Client.min_buffer_len,
/// 若非 null,则将 SSL 密钥记录到流中。创建此类流后,
/// 其他能够访问此流的进程就可以解密通过此 `Client`
/// 创建的连接上的全部流量。
ssl_key_log: ?*std.crypto.tls.Client.SslKeyLog = null,

/// 用于判定证书是否过期的时间。
///
/// 若为 `null`,客户端下次发起 HTTPS 请求时,
/// 会先检查时间并重新扫描系统根证书。
now: ?Io.Timestamp = null,

/// 可复用连接的池(包含当前正在使用的连接)。
connection_pool: ConnectionPool = .{},
/// 每个 `Connection` 为读取缓冲区分配此大小。
///
/// 如果全部 HTTP 标头无法容纳在这么多字节中,
/// `Request.wait` 将返回 `error.HttpHeadersOversize`。
read_buffer_size: usize = 8192,
/// 每个 `Connection` 为写入器缓冲区分配这么多内存。
write_buffer_size: usize = 1024,

/// 若已设置,全部 HTTP 流量都通过此第三方。
/// 客户端有活动连接时,不得修改此字段。
/// 指向外部拥有的内存的指针。
http_proxy: ?*Proxy = null,
/// 若填充此项,所有 https 流量均经由此第三方。
/// 客户端存在活动连接时,不得修改此字段。
/// 指针指向外部拥有的内存。
https_proxy: ?*Proxy = null,

/// 保存已打开连接以供复用的最近最少使用缓存。
pub const ConnectionPool = struct {
    mutex: Io.Mutex = .init,
    /// 当前正在使用的已打开连接。
    used: std.DoublyLinkedList = .{},
    /// 当前未使用的已打开连接。
    free: std.DoublyLinkedList = .{},
    free_len: usize = 0,
    free_size: usize = 32,

    /// 判定连接是否匹配的条件。
    pub const Criteria = struct {
        host: HostName,
        port: u16,
        protocol: Protocol,
    };

    /// 从连接池查找并获取符合条件的连接。
    /// 未找到连接时返回 null。
    ///
    /// 线程安全。
    pub fn findConnection(pool: *ConnectionPool, io: Io, criteria: Criteria) Io.Cancelable!?*Connection {
        try pool.mutex.lock(io);
        defer pool.mutex.unlock(io);

        var next = pool.free.last;
        while (next) |node| : (next = node.prev) {
            const connection: *Connection = @alignCast(@fieldParentPtr("pool_node", node));
            if (connection.protocol != criteria.protocol) continue;
            if (connection.port != criteria.port) continue;

            // 域名不区分大小写(RFC 5890,第 2.3.2.4 节)。
            if (!connection.host().eql(criteria.host)) continue;

            pool.acquireUnsafe(connection);
            return connection;
        }

        return null;
    }

    /// 从连接池获取已有连接。此函数非线程安全。
    pub fn acquireUnsafe(pool: *ConnectionPool, connection: *Connection) void {
        pool.free.remove(&connection.pool_node);
        pool.free_len -= 1;

        pool.used.append(&connection.pool_node);
    }

    /// 从连接池获取现有连接。此函数是线程安全的。
    pub fn acquire(pool: *ConnectionPool, io: Io, connection: *Connection) Io.Cancelable!void {
        try pool.mutex.lock(io);
        defer pool.mutex.unlock(io);

        return pool.acquireUnsafe(connection);
    }

    /// 尝试将连接释放回连接池。
    /// 如果连接已标记为正在关闭,则改为关闭它。
    ///
    /// 线程安全。
    pub fn release(pool: *ConnectionPool, connection: *Connection, io: Io) void {
        pool.mutex.lockUncancelable(io);
        defer pool.mutex.unlock(io);

        pool.used.remove(&connection.pool_node);

        if (connection.closing or pool.free_size == 0) return connection.destroy(io);

        if (pool.free_len >= pool.free_size) {
            const popped: *Connection = @alignCast(@fieldParentPtr("pool_node", pool.free.popFirst().?));
            pool.free_len -= 1;

            popped.destroy(io);
        }

        if (connection.proxied) {
            // 代理连接放在队列末尾,始终优先尝试直接连接
            pool.free.prepend(&connection.pool_node);
        } else {
            pool.free.append(&connection.pool_node);
        }

        pool.free_len += 1;
    }

    /// 将新创建的节点加入已使用连接池。此函数线程安全。
    pub fn addUsed(pool: *ConnectionPool, io: Io, connection: *Connection) Io.Cancelable!void {
        try pool.mutex.lock(io);
        defer pool.mutex.unlock(io);

        pool.used.append(&connection.pool_node);
    }

    /// 调整连接池大小。
    ///
    /// 若新大小小于当前大小,则关闭空闲连接,直到连接池达到新大小。
    ///
    /// 线程安全。
    pub fn resize(pool: *ConnectionPool, io: Io, new_size: usize) Io.Cancelable!void {
        try pool.mutex.lock(io);
        defer pool.mutex.unlock(io);

        while (pool.free_len > new_size) {
            const popped: *Connection = @alignCast(@fieldParentPtr("pool_node", pool.free.popFirst().?));
            pool.free_len -= 1;

            popped.destroy(io);
        }

        pool.free_size = new_size;
    }

    /// 释放连接池并关闭其中所有连接。
    ///
    /// 此后对连接池的所有操作都会死锁。
    ///
    /// 线程安全。
    pub fn deinit(pool: *ConnectionPool, io: Io) void {
        pool.mutex.lockUncancelable(io);

        var next = pool.free.first;
        while (next) |node| {
            const connection: *Connection = @alignCast(@fieldParentPtr("pool_node", node));
            next = node.next;
            connection.destroy(io);
        }

        next = pool.used.first;
        while (next) |node| {
            const connection: *Connection = @alignCast(@fieldParentPtr("pool_node", node));
            next = node.next;
            connection.destroy(io);
        }

        pool.* = undefined;
    }
};

pub const Protocol = enum {
    plain,
    tls,

    fn port(protocol: Protocol) u16 {
        return switch (protocol) {
            .plain => 80,
            .tls => 443,
        };
    }

    pub fn fromScheme(scheme: []const u8) ?Protocol {
        const protocol_map = std.StaticStringMap(Protocol).initComptime(.{
            .{ "http", .plain },
            .{ "ws", .plain },
            .{ "https", .tls },
            .{ "wss", .tls },
        });
        return protocol_map.get(scheme);
    }

    pub fn fromUri(uri: Uri) ?Protocol {
        return fromScheme(uri.scheme);
    }
};

pub const Connection = struct {
    client: *Client,
    stream_writer: Io.net.Stream.Writer,
    stream_reader: Io.net.Stream.Reader,
    /// `ConnectionPool.used` 或 `ConnectionPool.free` 中的条目。
    pool_node: std.DoublyLinkedList.Node,
    port: u16,
    host_len: u8,
    proxied: bool,
    closing: bool,
    protocol: Protocol,

    const Plain = struct {
        connection: Connection,

        fn create(
            client: *Client,
            remote_host: HostName,
            port: u16,
            stream: Io.net.Stream,
        ) error{OutOfMemory}!*Plain {
            const io = client.io;
            const gpa = client.allocator;
            const alloc_len = allocLen(client, remote_host.bytes.len);
            const base = try gpa.alignedAlloc(u8, .of(Plain), alloc_len);
            errdefer gpa.free(base);
            const host_buffer = base[@sizeOf(Plain)..][0..remote_host.bytes.len];
            const socket_read_buffer = host_buffer.ptr[host_buffer.len..][0..client.read_buffer_size];
            const socket_write_buffer = socket_read_buffer.ptr[socket_read_buffer.len..][0..client.write_buffer_size];
            assert(base.ptr + alloc_len == socket_write_buffer.ptr + socket_write_buffer.len);
            @memcpy(host_buffer, remote_host.bytes);
            const plain: *Plain = @ptrCast(base);
            plain.* = .{
                .connection = .{
                    .client = client,
                    .stream_writer = stream.writer(io, socket_write_buffer),
                    .stream_reader = stream.reader(io, socket_read_buffer),
                    .pool_node = .{},
                    .port = port,
                    .host_len = @intCast(remote_host.bytes.len),
                    .proxied = false,
                    .closing = false,
                    .protocol = .plain,
                },
            };
            return plain;
        }

        fn destroy(plain: *Plain) void {
            const c = &plain.connection;
            const gpa = c.client.allocator;
            const base: [*]align(@alignOf(Plain)) u8 = @ptrCast(plain);
            gpa.free(base[0..allocLen(c.client, c.host_len)]);
        }

        fn allocLen(client: *Client, host_len: usize) usize {
            return @sizeOf(Plain) + host_len + client.read_buffer_size + client.write_buffer_size;
        }

        fn host(plain: *Plain) HostName {
            const base: [*]u8 = @ptrCast(plain);
            return .{ .bytes = base[@sizeOf(Plain)..][0..plain.connection.host_len] };
        }
    };

    const Tls = struct {
        client: std.crypto.tls.Client,
        connection: Connection,

        /// 断言 `client.now` 非空。
        fn create(
            client: *Client,
            remote_host: HostName,
            port: u16,
            stream: Io.net.Stream,
        ) !*Tls {
            const io = client.io;
            const gpa = client.allocator;
            const alloc_len = allocLen(client, remote_host.bytes.len);
            const base = try gpa.alignedAlloc(u8, .of(Tls), alloc_len);
            errdefer gpa.free(base);
            const host_buffer = base[@sizeOf(Tls)..][0..remote_host.bytes.len];
            // TLS 客户端需要足以容纳最大加密帧的缓冲区,
            // HTTP 消息体读取器需要足以容纳整个
            // HTTP 头的缓冲区。因此需要合并后的上界。
            const tls_read_buffer_len = client.tls_buffer_size + client.read_buffer_size;
            const tls_read_buffer = host_buffer.ptr[host_buffer.len..][0..tls_read_buffer_len];
            const tls_write_buffer = tls_read_buffer.ptr[tls_read_buffer.len..][0..client.tls_buffer_size];
            const socket_write_buffer = tls_write_buffer.ptr[tls_write_buffer.len..][0..client.write_buffer_size];
            const socket_read_buffer = socket_write_buffer.ptr[socket_write_buffer.len..][0..client.tls_buffer_size];
            assert(base.ptr + alloc_len == socket_read_buffer.ptr + socket_read_buffer.len);
            @memcpy(host_buffer, remote_host.bytes);
            const tls: *Tls = @ptrCast(base);
            var random_buffer: [std.crypto.tls.Client.Options.entropy_len]u8 = undefined;
            io.random(&random_buffer);
            tls.* = .{
                .connection = .{
                    .client = client,
                    .stream_writer = stream.writer(io, tls_write_buffer),
                    .stream_reader = stream.reader(io, socket_read_buffer),
                    .pool_node = .{},
                    .port = port,
                    .host_len = @intCast(remote_host.bytes.len),
                    .proxied = false,
                    .closing = false,
                    .protocol = .tls,
                },
                // TODO: 若用户将 `now` 设为 null,此处 ca_bundle 存在数据竞争
                .client = std.crypto.tls.Client.init(
                    &tls.connection.stream_reader.interface,
                    &tls.connection.stream_writer.interface,
                    .{
                        .host = .{ .explicit = remote_host.bytes },
                        .ca = .{ .bundle = .{
                            .gpa = client.allocator,
                            .io = client.io,
                            .lock = &client.ca_bundle_lock,
                            .bundle = &client.ca_bundle,
                        } },
                        .ssl_key_log = client.ssl_key_log,
                        .read_buffer = tls_read_buffer,
                        .write_buffer = socket_write_buffer,
                        .entropy = &random_buffer,
                        .realtime_now = client.now.?,
                        // 这适用于 HTTPS,因为 HTTP 头包含
                        // 内容长度,可用于检测截断攻击。
                        .allow_truncation_attacks = true,
                    },
                ) catch |err| switch (err) {
                    error.WriteFailed => return tls.connection.stream_writer.err.?,
                    error.ReadFailed => return tls.connection.stream_reader.err.?,
                    else => |e| return e,
                },
            };
            return tls;
        }

        fn destroy(tls: *Tls) void {
            const c = &tls.connection;
            const gpa = c.client.allocator;
            const base: [*]align(@alignOf(Tls)) u8 = @ptrCast(tls);
            gpa.free(base[0..allocLen(c.client, c.host_len)]);
        }

        fn allocLen(client: *Client, host_len: usize) usize {
            const tls_read_buffer_len = client.tls_buffer_size + client.read_buffer_size;
            return @sizeOf(Tls) + host_len + tls_read_buffer_len + client.tls_buffer_size +
                client.write_buffer_size + client.tls_buffer_size;
        }

        fn host(tls: *Tls) HostName {
            const base: [*]u8 = @ptrCast(tls);
            return .{ .bytes = base[@sizeOf(Tls)..][0..tls.connection.host_len] };
        }
    };

    pub const ReadError = std.crypto.tls.Client.ReadError || Io.net.Stream.Reader.Error;

    pub fn getReadError(c: *const Connection) ?ReadError {
        return switch (c.protocol) {
            .tls => {
                if (disable_tls) unreachable;
                const tls: *const Tls = @alignCast(@fieldParentPtr("connection", c));
                return tls.client.read_err orelse c.stream_reader.err.?;
            },
            .plain => {
                return c.stream_reader.err.?;
            },
        };
    }

    fn getStream(c: *Connection) Io.net.Stream {
        return c.stream_reader.stream;
    }

    pub fn host(c: *Connection) HostName {
        return switch (c.protocol) {
            .tls => {
                if (disable_tls) unreachable;
                const tls: *Tls = @alignCast(@fieldParentPtr("connection", c));
                return tls.host();
            },
            .plain => {
                const plain: *Plain = @alignCast(@fieldParentPtr("connection", c));
                return plain.host();
            },
        };
    }

    /// 若未调用 `flush` 或 `end` 就调用此方法,数据将
    /// 被丢弃而不发送。
    pub fn destroy(c: *Connection, io: Io) void {
        c.stream_reader.stream.close(io);
        switch (c.protocol) {
            .tls => {
                if (disable_tls) unreachable;
                const tls: *Tls = @alignCast(@fieldParentPtr("connection", c));
                tls.destroy();
            },
            .plain => {
                const plain: *Plain = @alignCast(@fieldParentPtr("connection", c));
                plain.destroy();
            },
        }
    }

    /// 从客户端到服务器的 HTTP 协议数据。
    /// 它直接送往 `stream_writer` 或 TLS 客户端。
    pub fn writer(c: *Connection) *Writer {
        return switch (c.protocol) {
            .tls => {
                if (disable_tls) unreachable;
                const tls: *Tls = @alignCast(@fieldParentPtr("connection", c));
                return &tls.client.writer;
            },
            .plain => &c.stream_writer.interface,
        };
    }

    /// 从服务器到客户端的 HTTP 协议数据。
    /// 它直接来自 `stream_reader`,或来自 TLS 客户端。
    pub fn reader(c: *Connection) *Reader {
        return switch (c.protocol) {
            .tls => {
                if (disable_tls) unreachable;
                const tls: *Tls = @alignCast(@fieldParentPtr("connection", c));
                return &tls.client.reader;
            },
            .plain => &c.stream_reader.interface,
        };
    }

    pub fn flush(c: *Connection) Writer.Error!void {
        if (c.protocol == .tls) {
            if (disable_tls) unreachable;
            const tls: *Tls = @alignCast(@fieldParentPtr("connection", c));
            try tls.client.writer.flush();
        }
        try c.stream_writer.interface.flush();
    }

    /// 若连接为 TLS 连接,则发送 close_notify 警报。
    ///
    /// 刷新所有缓冲区。
    pub fn end(c: *Connection) Writer.Error!void {
        if (c.protocol == .tls) {
            if (disable_tls) unreachable;
            const tls: *Tls = @alignCast(@fieldParentPtr("connection", c));
            try tls.client.end();
        }
        try c.stream_writer.interface.flush();
    }
};

pub const Response = struct {
    request: *Request,
    /// 初始化响应消息体流时,此结构中的指针
    /// 将失效。
    head: Head,

    pub const Head = struct {
        bytes: []const u8,
        version: http.Version,
        status: http.Status,
        reason: []const u8,
        location: ?[]const u8 = null,
        content_type: ?[]const u8 = null,
        content_disposition: ?[]const u8 = null,

        keep_alive: bool,

        /// 若存在,则为响应消息体的字节数。
        content_length: ?u64 = null,

        transfer_encoding: http.TransferEncoding = .none,
        content_encoding: http.ContentEncoding = .identity,

        pub const ParseError = error{
            HttpConnectionHeaderUnsupported,
            HttpContentEncodingUnsupported,
            HttpHeaderContinuationsUnsupported,
            HttpHeadersInvalid,
            HttpTransferEncodingUnsupported,
            InvalidContentLength,
        };

        pub fn parse(bytes: []const u8) ParseError!Head {
            var res: Head = .{
                .bytes = bytes,
                .status = undefined,
                .reason = undefined,
                .version = undefined,
                .keep_alive = false,
            };
            var it = mem.splitSequence(u8, bytes, "\r\n");

            const first_line = it.first();
            if (first_line.len < 12) return error.HttpHeadersInvalid;

            const version: http.Version = switch (int64(first_line[0..8])) {
                int64("HTTP/1.0") => .@"HTTP/1.0",
                int64("HTTP/1.1") => .@"HTTP/1.1",
                else => return error.HttpHeadersInvalid,
            };
            if (first_line[8] != ' ') return error.HttpHeadersInvalid;
            const status: http.Status = @fromBackingInt(@intCast(parseInt3(first_line[9..12])));
            const reason = mem.trimStart(u8, first_line[12..], " ");

            res.version = version;
            res.status = status;
            res.reason = reason;
            res.keep_alive = switch (version) {
                .@"HTTP/1.0" => false,
                .@"HTTP/1.1" => true,
            };

            while (it.next()) |line| {
                if (line.len == 0) return res;
                switch (line[0]) {
                    ' ', '\t' => return error.HttpHeaderContinuationsUnsupported,
                    else => {},
                }

                var line_it = mem.splitScalar(u8, line, ':');
                const header_name = line_it.next().?;
                const header_value = mem.trim(u8, line_it.rest(), " \t");
                if (header_name.len == 0) return error.HttpHeadersInvalid;

                if (std.ascii.eqlIgnoreCase(header_name, "connection")) {
                    res.keep_alive = !std.ascii.eqlIgnoreCase(header_value, "close");
                } else if (std.ascii.eqlIgnoreCase(header_name, "content-type")) {
                    res.content_type = header_value;
                } else if (std.ascii.eqlIgnoreCase(header_name, "location")) {
                    res.location = header_value;
                } else if (std.ascii.eqlIgnoreCase(header_name, "content-disposition")) {
                    res.content_disposition = header_value;
                } else if (std.ascii.eqlIgnoreCase(header_name, "transfer-encoding")) {
                    // Transfer-Encoding: second, first
                    // Transfer-Encoding: deflate, chunked
                    var iter = mem.splitBackwardsScalar(u8, header_value, ',');

                    const first = iter.first();
                    const trimmed_first = mem.trim(u8, first, " ");

                    var next: ?[]const u8 = first;
                    if (std.meta.stringToEnum(http.TransferEncoding, trimmed_first)) |transfer| {
                        if (res.transfer_encoding != .none) return error.HttpHeadersInvalid; // 我们已有传输编码
                        res.transfer_encoding = transfer;

                        next = iter.next();
                    }

                    if (next) |second| {
                        const trimmed_second = mem.trim(u8, second, " ");

                        if (http.ContentEncoding.fromString(trimmed_second)) |transfer| {
                            if (res.content_encoding != .identity) return error.HttpHeadersInvalid; // 不支持双重压缩
                            res.content_encoding = transfer;
                        } else {
                            return error.HttpTransferEncodingUnsupported;
                        }
                    }

                    if (iter.next()) |_| return error.HttpTransferEncodingUnsupported;
                } else if (std.ascii.eqlIgnoreCase(header_name, "content-length")) {
                    const content_length = std.fmt.parseInt(u64, header_value, 10) catch return error.InvalidContentLength;

                    if (res.content_length != null and res.content_length != content_length) return error.HttpHeadersInvalid;

                    res.content_length = content_length;
                } else if (std.ascii.eqlIgnoreCase(header_name, "content-encoding")) {
                    if (res.content_encoding != .identity) return error.HttpHeadersInvalid;

                    const trimmed = mem.trim(u8, header_value, " ");

                    if (http.ContentEncoding.fromString(trimmed)) |ce| {
                        res.content_encoding = ce;
                    } else {
                        return error.HttpContentEncodingUnsupported;
                    }
                }
            }
            return error.HttpHeadersInvalid; // 缺少空行
        }

        test parse {
            const response_bytes = "HTTP/1.1 200 OK\r\n" ++
                "LOcation:url\r\n" ++
                "content-tYpe: text/plain\r\n" ++
                "content-disposition:attachment; filename=example.txt \r\n" ++
                "content-Length:10\r\n" ++
                "TRansfer-encoding:\tdeflate, chunked \r\n" ++
                "connectioN:\t keep-alive \r\n\r\n";

            const head = try Head.parse(response_bytes);

            try testing.expectEqual(.@"HTTP/1.1", head.version);
            try testing.expectEqualStrings("OK", head.reason);
            try testing.expectEqual(.ok, head.status);

            try testing.expectEqualStrings("url", head.location.?);
            try testing.expectEqualStrings("text/plain", head.content_type.?);
            try testing.expectEqualStrings("attachment; filename=example.txt", head.content_disposition.?);

            try testing.expectEqual(true, head.keep_alive);
            try testing.expectEqual(10, head.content_length.?);
            try testing.expectEqual(.chunked, head.transfer_encoding);
            try testing.expectEqual(.deflate, head.content_encoding);
        }

        pub fn iterateHeaders(h: Head) http.HeaderIterator {
            return .init(h.bytes);
        }

        test iterateHeaders {
            const response_bytes = "HTTP/1.1 200 OK\r\n" ++
                "LOcation:url\r\n" ++
                "content-tYpe: text/plain\r\n" ++
                "content-disposition:attachment; filename=example.txt \r\n" ++
                "content-Length:10\r\n" ++
                "TRansfer-encoding:\tdeflate, chunked \r\n" ++
                "connectioN:\t keep-alive \r\n\r\n";

            const head = try Head.parse(response_bytes);
            var it = head.iterateHeaders();
            {
                const header = it.next().?;
                try testing.expectEqualStrings("LOcation", header.name);
                try testing.expectEqualStrings("url", header.value);
                try testing.expect(!it.is_trailer);
            }
            {
                const header = it.next().?;
                try testing.expectEqualStrings("content-tYpe", header.name);
                try testing.expectEqualStrings("text/plain", header.value);
                try testing.expect(!it.is_trailer);
            }
            {
                const header = it.next().?;
                try testing.expectEqualStrings("content-disposition", header.name);
                try testing.expectEqualStrings("attachment; filename=example.txt", header.value);
                try testing.expect(!it.is_trailer);
            }
            {
                const header = it.next().?;
                try testing.expectEqualStrings("content-Length", header.name);
                try testing.expectEqualStrings("10", header.value);
                try testing.expect(!it.is_trailer);
            }
            {
                const header = it.next().?;
                try testing.expectEqualStrings("TRansfer-encoding", header.name);
                try testing.expectEqualStrings("deflate, chunked", header.value);
                try testing.expect(!it.is_trailer);
            }
            {
                const header = it.next().?;
                try testing.expectEqualStrings("connectioN", header.name);
                try testing.expectEqualStrings("keep-alive", header.value);
                try testing.expect(!it.is_trailer);
            }
            try testing.expectEqual(null, it.next());
        }

        inline fn int64(array: *const [8]u8) u64 {
            return @bitCast(array.*);
        }

        fn parseInt3(text: *const [3]u8) u10 {
            const nnn: @Vector(3, u8) = text.*;
            const zero: @Vector(3, u8) = .{ '0', '0', '0' };
            const mmm: @Vector(3, u10) = .{ 100, 10, 1 };
            return @reduce(.Add, (nnn -% zero) *% mmm);
        }

        test parseInt3 {
            const expectEqual = testing.expectEqual;
            try expectEqual(@as(u10, 0), parseInt3("000"));
            try expectEqual(@as(u10, 418), parseInt3("418"));
            try expectEqual(@as(u10, 999), parseInt3("999"));
        }

        /// 当 `Head` 的字符串内存失效时调用此函数,
        /// 帮助程序员避免缺陷。
        fn invalidateStrings(h: *Head) void {
            h.bytes = undefined;
            h.reason = undefined;
            if (h.location) |*s| s.* = undefined;
            if (h.content_type) |*s| s.* = undefined;
            if (h.content_disposition) |*s| s.* = undefined;
        }
    };

    /// 如果已协商正文压缩,则返回压缩字节。
    ///
    /// 如果返回的 `Reader` 返回 `error.ReadFailed`,
    /// 可通过 `bodyErr` 取得具体错误。
    ///
    /// 断言此函数仅调用一次。
    ///
    /// 另请参见:
    /// * `readerDecompressing`
    pub fn reader(response: *Response, transfer_buffer: []u8) *Reader {
        response.head.invalidateStrings();
        const req = response.request;
        if (req.method == .HEAD) return .ending;
        const head = &response.head;
        return req.reader.bodyReader(transfer_buffer, head.transfer_encoding, head.content_length);
    }

    /// 若已协商使用压缩消息体,则返回解压后的字节。
    ///
    /// 若返回的 `Reader` 返回 `error.ReadFailed`,可通过
    /// `bodyErr` 获取错误。
    ///
    /// 断言此函数仅调用一次。
    ///
    /// 另见:
    /// * `reader`
    pub fn readerDecompressing(
        response: *Response,
        transfer_buffer: []u8,
        decompress: *http.Decompress,
        decompress_buffer: []u8,
    ) *Reader {
        response.head.invalidateStrings();
        const head = &response.head;
        return response.request.reader.bodyReaderDecompressing(
            transfer_buffer,
            head.transfer_encoding,
            head.content_length,
            head.content_encoding,
            decompress,
            decompress_buffer,
        );
    }

    /// 从 `reader` 或 `readerDecompressing` 返回的 `Reader`
    /// 收到 `error.ReadFailed` 后,使用此函数
    /// 访问更具体的错误码。
    pub fn bodyErr(response: *const Response) ?http.Reader.BodyError {
        return response.request.reader.body_err;
    }

    pub fn iterateTrailers(response: *const Response) http.HeaderIterator {
        const r = &response.request.reader;
        assert(r.state == .ready);
        return .{
            .bytes = r.trailers,
            .index = 0,
            .is_trailer = true,
        };
    }
};

pub const Request = struct {
    /// 提供此字段,使客户端能够观察重定向后的 URI。
    ///
    /// 其底层内存在创建请求时由 API 用户
    /// 外部提供,之后又通过 `redirect_buffer` 外部提供给
    /// `receiveHead`。
    uri: Uri,
    client: *Client,
    /// 连接释放时此值为 null。
    connection: ?*Connection,
    reader: http.Reader,
    keep_alive: bool,

    method: http.Method,
    version: http.Version = .@"HTTP/1.1",
    transfer_encoding: TransferEncoding,
    redirect_behavior: RedirectBehavior,
    accept_encoding: @TypeOf(default_accept_encoding) = default_accept_encoding,

    /// 请求是否应在发送请求体之前处理 100-continue 响应。
    handle_continue: bool,

    /// 具有默认行为且允许覆盖该行为的标准头字段。
    headers: Headers,

    /// 在 `receiveHead` 中赋值;在 `deinit` 中用于判断是否需要
    /// 丢弃响应体以复用连接。
    response_content_length: ?u64 = null,
    /// 在 `receiveHead` 中赋值;在 `deinit` 中用于判断是否需要
    /// 丢弃响应体以复用连接。
    response_transfer_encoding: http.TransferEncoding = .none,
    /// 在 `deinit` 中用于判断请求体是否已经发送,从而确定
    /// 连接是否可以安全复用。
    payload_pending: bool = false,

    /// 即使跟随重定向至其他域名,也会保留
    /// 这些头部。
    /// 所有权属于外部;必须比 Request 存活更久。
    extra_headers: []const http.Header,

    /// 跟随重定向到其他域时会移除这些头字段。
    /// 所有权属于外部;生存期必须长于 Request。
    ///
    privileged_headers: []const http.Header,

    pub const default_accept_encoding: [@typeInfo(http.ContentEncoding).@"enum".field_names.len]bool = b: {
        var result: [@typeInfo(http.ContentEncoding).@"enum".field_names.len]bool = @splat(false);
        result[@backingInt(http.ContentEncoding.gzip)] = true;
        result[@backingInt(http.ContentEncoding.deflate)] = true;
        result[@backingInt(http.ContentEncoding.identity)] = true;
        break :b result;
    };

    pub const TransferEncoding = union(enum) {
        content_length: u64,
        chunked: void,
        none: void,
    };

    pub const Headers = struct {
        host: Value = .default,
        authorization: Value = .default,
        user_agent: Value = .default,
        connection: Value = .default,
        accept_encoding: Value = .default,
        content_type: Value = .default,

        pub const Value = union(enum) {
            default,
            omit,
            override: []const u8,
        };
    };

    /// 除 `not_allowed` 或 `unhandled` 以外的任何值,表示仍允许的重定向次数。
    ///
    pub const RedirectBehavior = enum(u16) {
        /// 下一次重定向将导致错误。
        not_allowed = 0,
        /// 将重定向交给客户端,以直接分析重定向响应。
        ///
        unhandled = std.math.maxInt(u16),
        _,

        pub fn init(n: u16) RedirectBehavior {
            assert(n != std.math.maxInt(u16));
            return @fromBackingInt(@intCast(n));
        }

        pub fn subtractOne(rb: *RedirectBehavior) void {
            switch (rb.*) {
                .not_allowed => unreachable,
                .unhandled => unreachable,
                _ => rb.* = @fromBackingInt(@intCast(@backingInt(rb.*) - 1)),
            }
        }

        pub fn remaining(rb: RedirectBehavior) u16 {
            assert(rb != .unhandled);
            return @backingInt(rb);
        }
    };

    /// 将请求的 `Connection` 归还至 `Client` 的连接池。
    pub fn deinit(r: *Request) void {
        const io = r.client.io;
        if (r.connection) |connection| {
            connection.closing = connection.closing or switch (r.reader.state) {
                .ready => false,
                .received_head => c: {
                    if (r.payload_pending) break :c true;
                    if (r.method == .HEAD) break :c false;

                    const reader = r.reader.bodyReader(&.{}, r.response_transfer_encoding, r.response_content_length);
                    _ = reader.discardRemaining() catch |err| switch (err) {
                        error.ReadFailed => break :c true,
                    };
                    break :c r.reader.state != .ready;
                },
                else => true,
            };
            r.client.connection_pool.release(connection, io);
        }
        r.* = undefined;
    }

    /// 发送并刷新一个仅含 HTTP 头部、无消息体的完整请求。
    pub fn sendBodiless(r: *Request) Writer.Error!void {
        try sendBodilessUnflushed(r);
        try r.connection.?.flush();
    }

    /// 发送完整请求但不刷新,仅包含 HTTP 头部,不包含消息体。
    pub fn sendBodilessUnflushed(r: *Request) Writer.Error!void {
        assert(r.transfer_encoding == .none);
        try sendHead(r);
    }

    /// 通过连接传输 HTTP 头部并刷新。
    ///
    /// 另见:
    /// * `sendBodyUnflushed`
    pub fn sendBody(r: *Request, buffer: []u8) Writer.Error!http.BodyWriter {
        const result = try sendBodyUnflushed(r, buffer);
        try r.connection.?.flush();
        return result;
    }

    /// 通过连接传输 HTTP 头部和消息体,并刷新。
    pub fn sendBodyComplete(r: *Request, body: []u8) Writer.Error!void {
        r.transfer_encoding = .{ .content_length = body.len };
        var bw = try sendBodyUnflushed(r, body);
        bw.writer.end = body.len;
        try bw.end();
        try r.connection.?.flush();
    }

    /// 通过连接传输 HTTP 头部;在调用 `BodyWriter.flush` 或 `BodyWriter.end` 前不会刷新。
    ///
    /// 另见:
    /// * `sendBody`
    ///
    pub fn sendBodyUnflushed(r: *Request, buffer: []u8) Writer.Error!http.BodyWriter {
        r.payload_pending = true;
        try sendHead(r);
        const http_protocol_output = r.connection.?.writer();
        return switch (r.transfer_encoding) {
            .chunked => .{
                .http_protocol_output = http_protocol_output,
                .state = .init_chunked,
                .client_request = r,
                .writer = .{
                    .buffer = buffer,
                    .vtable = &.{
                        .drain = http.BodyWriter.chunkedDrain,
                        .sendFile = http.BodyWriter.chunkedSendFile,
                    },
                },
            },
            .content_length => |len| .{
                .http_protocol_output = http_protocol_output,
                .state = .{ .content_length = len },
                .client_request = r,
                .writer = .{
                    .buffer = buffer,
                    .vtable = &.{
                        .drain = http.BodyWriter.contentLengthDrain,
                        .sendFile = http.BodyWriter.contentLengthSendFile,
                    },
                },
            },
            .none => .{
                .http_protocol_output = http_protocol_output,
                .state = .none,
                .client_request = r,
                .writer = .{
                    .buffer = buffer,
                    .vtable = &.{
                        .drain = http.BodyWriter.noneDrain,
                        .sendFile = http.BodyWriter.noneSendFile,
                    },
                },
            },
        };
    }

    /// 发送 HTTP 头但不刷新。
    fn sendHead(r: *Request) Writer.Error!void {
        const uri = r.uri;
        const connection = r.connection.?;
        const w = connection.writer();

        try w.writeAll(@tagName(r.method));
        try w.writeByte(' ');

        if (r.method == .CONNECT) {
            try uri.writeToStream(w, .{ .authority = true });
        } else {
            try uri.writeToStream(w, .{
                .scheme = connection.proxied,
                .authentication = connection.proxied,
                .authority = connection.proxied,
                .path = true,
                .query = true,
            });
        }
        try w.writeByte(' ');
        try w.writeAll(@tagName(r.version));
        try w.writeAll("\r\n");

        if (try emitOverridableHeader("host: ", r.headers.host, w)) {
            try w.writeAll("host: ");
            try uri.writeToStream(w, .{ .authority = true });
            try w.writeAll("\r\n");
        }

        if (try emitOverridableHeader("authorization: ", r.headers.authorization, w)) {
            if (uri.user != null or uri.password != null) {
                try w.writeAll("authorization: ");
                try basic_authorization.write(uri, w);
                try w.writeAll("\r\n");
            }
        }

        if (try emitOverridableHeader("user-agent: ", r.headers.user_agent, w)) {
            try w.writeAll("user-agent: zig/");
            try w.writeAll(builtin.zig_version_string);
            try w.writeAll(" (std.http)\r\n");
        }

        if (try emitOverridableHeader("connection: ", r.headers.connection, w)) {
            if (r.keep_alive) {
                try w.writeAll("connection: keep-alive\r\n");
            } else {
                try w.writeAll("connection: close\r\n");
            }
        }

        if (try emitOverridableHeader("accept-encoding: ", r.headers.accept_encoding, w)) {
            try w.writeAll("accept-encoding: ");
            for (r.accept_encoding, 0..) |enabled, i| {
                if (!enabled) continue;
                const tag: http.ContentEncoding = @fromBackingInt(@intCast(i));
                if (tag == .identity) continue;
                const tag_name = @tagName(tag);
                try w.ensureUnusedCapacity(tag_name.len + 2);
                try w.writeAll(tag_name);
                try w.writeAll(", ");
            }
            w.undo(2);
            try w.writeAll("\r\n");
        }

        switch (r.transfer_encoding) {
            .chunked => try w.writeAll("transfer-encoding: chunked\r\n"),
            .content_length => |len| try w.print("content-length: {d}\r\n", .{len}),
            .none => {},
        }

        if (try emitOverridableHeader("content-type: ", r.headers.content_type, w)) {
            // 未提供 content-type 时,默认省略它,
            // 因为 "application/octet-stream" 是冗余的。
        }

        for (r.extra_headers) |header| {
            assert(header.name.len != 0);

            try w.writeAll(header.name);
            try w.writeAll(": ");
            try w.writeAll(header.value);
            try w.writeAll("\r\n");
        }

        if (connection.proxied) proxy: {
            const proxy = switch (connection.protocol) {
                .plain => r.client.http_proxy,
                .tls => r.client.https_proxy,
            } orelse break :proxy;

            const authorization = proxy.authorization orelse break :proxy;
            try w.writeAll("proxy-authorization: ");
            try w.writeAll(authorization);
            try w.writeAll("\r\n");
        }

        try w.writeAll("\r\n");
    }

    pub const ReceiveHeadError = http.Reader.HeadError || ConnectError || error{
        /// 服务器发送了不符合 HTTP 协议的标头。
        ///
        /// 若要获得更详细的诊断信息,可将 `http.Reader.head_buffer`
        /// 直接传给 `Request.Head.parse`。
        HttpHeadersInvalid,
        TooManyHttpRedirects,
        /// 可在发送请求体之前调用 `receiveHead`,
        /// 以避免此情况。
        RedirectRequiresResend,
        HttpRedirectLocationMissing,
        HttpRedirectLocationOversize,
        HttpRedirectLocationInvalid,
        HttpContentEncodingUnsupported,
        HttpChunkInvalid,
        HttpChunkTruncated,
        HttpHeadersOversize,
        UnsupportedUriScheme,

        /// 发送请求失败。错误码可在 `Connection` 对象中获取。
        ///
        WriteFailed,
    };

    /// 如果处理重定向且请求没有载荷,此函数会自动跟随重定向。
    ///
    /// 若存在请求载荷,则返回 `error.RedirectRequiresResend`。
    ///
    /// 此函数接受辅助缓冲区,用于存储可能需要与先前 URI 合并、且大小任意的 URI。这些数据必须跨连接保持有效;输入缓冲区则位于连接中。
    ///
    /// `redirect_buffer` 的生存期必须覆盖对 `Request.uri` 的访问。若将超出缓冲区容量,则改为返回 `error.HttpRedirectLocationOversize`。若不处理重定向,此缓冲区可以为空。RFC 9110 建议其大小至少为 8000 字节。
    ///
    /// 若此操作以 `error.ReadFailed` 失败,可调用 `r.connection` 的 `Connection.getReadError` 方法获取详细信息。
    ///
    ///
    ///
    ///
    ///
    ///
    ///
    ///
    ///
    pub fn receiveHead(r: *Request, redirect_buffer: []u8) ReceiveHeadError!Response {
        var aux_buf = redirect_buffer;
        while (true) {
            // 此 while 循环用于处理重定向,因此请求的连接
            // 可能与上一次迭代不同。不过,仍保证
            // 每次循环迭代时该连接均非 null。
            const connection = r.connection.?;

            const head_buffer = r.reader.receiveHead() catch |err| {
                // 此处失败意味着该连接无法再复用。
                connection.closing = true;
                return err;
            };
            const response: Response = .{
                .request = r,
                .head = Response.Head.parse(head_buffer) catch return error.HttpHeadersInvalid,
            };
            const head = &response.head;

            if (head.status == .@"continue") {
                if (r.handle_continue) continue;
                r.response_transfer_encoding = head.transfer_encoding;
                r.response_content_length = head.content_length;
                return response; // 我们未处理 100-continue
            }

            if (r.method == .CONNECT and head.status.class() == .success) {
                // 此连接不再使用 HTTP。
                connection.closing = false;
                r.response_transfer_encoding = head.transfer_encoding;
                r.response_content_length = head.content_length;
                return response;
            }

            connection.closing = !head.keep_alive or !r.keep_alive;

            // 对 HEAD 请求的任何响应,以及状态码为 1xx
            // 信息响应、204 无内容或 304 未修改的任何响应,
            // 都始终由标头字段之后的第一个空行
            // 终止,不受消息中存在的
            // 标头字段影响。
            if (r.method == .HEAD or head.status.class() == .informational or
                head.status == .no_content or head.status == .not_modified)
            {
                r.response_transfer_encoding = head.transfer_encoding;
                r.response_content_length = head.content_length;
                return response;
            }

            if (head.status.class() == .redirect and r.redirect_behavior != .unhandled) {
                if (r.redirect_behavior == .not_allowed) {
                    // 跳过消息体后,仍可复用连接。
                    const reader = r.reader.bodyReader(&.{}, head.transfer_encoding, head.content_length);
                    _ = reader.discardRemaining() catch |err| switch (err) {
                        error.ReadFailed => connection.closing = true,
                    };
                    return error.TooManyHttpRedirects;
                }
                try r.redirect(head, &aux_buf);
                try r.sendBodiless();
                continue;
            }

            if (!r.accept_encoding[@backingInt(head.content_encoding)])
                return error.HttpContentEncodingUnsupported;

            r.response_transfer_encoding = head.transfer_encoding;
            r.response_content_length = head.content_length;
            return response;
        }
    }

    /// 此函数接受辅助缓冲区,用于存储任意长度的 URI。该 URI 可能需要与前一个 URI 合并,且其数据必须跨不同连接存活,而输入缓冲区位于连接内部。
    ///
    /// `aux_buf` 的生命周期必须覆盖对 `Request.uri` 的全部访问。
    ///
    ///
    ///
    fn redirect(r: *Request, head: *const Response.Head, aux_buf: *[]u8) !void {
        const io = r.client.io;
        const new_location = head.location orelse return error.HttpRedirectLocationMissing;
        if (new_location.len > aux_buf.*.len) return error.HttpRedirectLocationOversize;
        const location = aux_buf.*[0..new_location.len];
        @memcpy(location, new_location);
        {
            // 跳过重定向响应消息体,使连接保持正确状态。这会使 `new_location` 失效。
            //
            const reader = r.reader.bodyReader(&.{}, head.transfer_encoding, head.content_length);
            _ = reader.discardRemaining() catch |err| switch (err) {
                error.ReadFailed => return r.reader.body_err.?,
            };
        }
        const new_uri = r.uri.resolveInPlace(location.len, aux_buf) catch |err| switch (err) {
            error.UnexpectedCharacter => return error.HttpRedirectLocationInvalid,
            error.InvalidFormat => return error.HttpRedirectLocationInvalid,
            error.InvalidPort => return error.HttpRedirectLocationInvalid,
            error.InvalidHostName => return error.HttpRedirectLocationInvalid,
            error.NoSpaceLeft => return error.HttpRedirectLocationOversize,
        };

        const protocol = Protocol.fromUri(new_uri) orelse return error.UnsupportedUriScheme;
        const old_connection = r.connection.?;
        const old_host = old_connection.host();
        var new_host_name_buffer: [HostName.max_len]u8 = undefined;
        const new_host = HostName.fromUri(new_uri, &new_host_name_buffer) catch |err| switch (err) {
            error.UriMissingHost => return error.HttpRedirectLocationInvalid,
            error.InvalidHostName => return error.HttpRedirectLocationInvalid,
            error.NameTooLong => return error.HttpRedirectLocationOversize,
        };
        const keep_privileged_headers =
            std.ascii.eqlIgnoreCase(r.uri.scheme, new_uri.scheme) and
            old_host.sameParentDomain(new_host);

        r.client.connection_pool.release(old_connection, io);
        r.connection = null;

        if (!keep_privileged_headers) {
            // 重定向到其他域时,移除特权头字段。
            r.privileged_headers = &.{};
        }

        if (switch (head.status) {
            .see_other => true,
            .moved_permanently, .found => r.method == .POST,
            else => false,
        }) {
            // 重定向为 GET 时,必须更改方法并移除消息体。
            r.method = .GET;
            r.transfer_encoding = .none;
            r.headers.content_type = .omit;
        }

        if (r.transfer_encoding != .none) {
            // 请求消息体已发送。请求仍然
            // 处于有效状态,但必须
            // 手动处理重定向。
            return error.RedirectRequiresResend;
        }

        const new_connection = try r.client.connect(new_host, uriPort(new_uri, protocol), protocol);
        r.uri = new_uri;
        r.connection = new_connection;
        r.reader = .{
            .in = new_connection.reader(),
            .state = .ready,
            // 调用 `http.Reader.bodyReader` 时填充。
            .interface = undefined,
            .max_head_len = r.client.read_buffer_size,
            .side = .response,
        };
        r.redirect_behavior.subtractOne();
    }

    /// 若需要默认行为则返回 true,否则处理
    /// 头部的写入(或不写入)。
    fn emitOverridableHeader(prefix: []const u8, v: Headers.Value, bw: *Writer) Writer.Error!bool {
        switch (v) {
            .default => return true,
            .omit => return false,
            .override => |x| {
                var vecs: [3][]const u8 = .{ prefix, x, "\r\n" };
                try bw.writeVecAll(&vecs);
                return false;
            },
        }
    }
};

pub const Proxy = struct {
    protocol: Protocol,
    host: HostName,
    authorization: ?[]const u8,
    port: u16,
    supports_connect: bool,
};

/// 释放与客户端关联的全部资源。
///
/// 调用此函数前,必须反初始化所有待处理请求并释放所有活动连接。
///
pub fn deinit(client: *Client) void {
    const io = client.io;
    assert(client.connection_pool.used.first == null); // 仍有活动请求。

    client.connection_pool.deinit(io);
    if (!disable_tls) client.ca_bundle.deinit(client.allocator);

    client.* = undefined;
}

/// 通过标准代理环境变量填充 `http_proxy` 和 `https_proxy`。
/// 断言客户端没有活动连接。
/// 使用 `arena` 进行少量小型分配;这些分配的生存期必须长于客户端,
/// 或至少持续到这些字段被设置为其他值。
pub fn initDefaultProxies(client: *Client, arena: Allocator, environ_map: *const std.process.Environ.Map) !void {
    const io = client.io;

    // 阻止创建任何新连接。
    try client.connection_pool.mutex.lock(io);
    defer client.connection_pool.mutex.unlock(io);

    assert(client.connection_pool.used.first == null); // 存在活动请求。

    if (client.http_proxy == null) {
        client.http_proxy = try createProxyFromEnvVar(arena, environ_map, &.{
            "http_proxy", "HTTP_PROXY", "all_proxy", "ALL_PROXY",
        });
    }

    if (client.https_proxy == null) {
        client.https_proxy = try createProxyFromEnvVar(arena, environ_map, &.{
            "https_proxy", "HTTPS_PROXY", "all_proxy", "ALL_PROXY",
        });
    }
}

fn createProxyFromEnvVar(
    arena: Allocator,
    environ_map: *const std.process.Environ.Map,
    env_var_names: []const []const u8,
) !?*Proxy {
    const content = for (env_var_names) |name| {
        const content = environ_map.get(name) orelse continue;
        if (content.len == 0) continue;
        break content;
    } else return null;

    const uri = Uri.parse(content) catch try Uri.parseAfterScheme("http", content);
    const protocol = Protocol.fromUri(uri) orelse return null;
    var host_buf: [HostName.max_len]u8 = undefined;
    const raw_host = try HostName.fromUri(uri, &host_buf);

    const authorization: ?[]const u8 = if (uri.user != null or uri.password != null) a: {
        const authorization = try arena.alloc(u8, basic_authorization.valueLengthFromUri(uri));
        assert(basic_authorization.value(uri, authorization).len == authorization.len);
        break :a authorization;
    } else null;

    const proxy = try arena.create(Proxy);
    proxy.* = .{
        .protocol = protocol,
        .host = .{ .bytes = try arena.dupe(u8, raw_host.bytes) },
        .authorization = authorization,
        .port = uriPort(uri, protocol),
        .supports_connect = true,
    };
    return proxy;
}

pub const basic_authorization = struct {
    pub const max_user_len = 255;
    pub const max_password_len = 255;
    pub const max_value_len = valueLength(max_user_len, max_password_len);

    pub fn valueLength(user_len: usize, password_len: usize) usize {
        return "Basic ".len + std.base64.standard.Encoder.calcSize(user_len + 1 + password_len);
    }

    pub fn valueLengthFromUri(uri: Uri) usize {
        const user: Uri.Component = uri.user orelse .empty;
        const password: Uri.Component = uri.password orelse .empty;

        var dw: Writer.Discarding = .init(&.{});
        user.formatUser(&dw.writer) catch unreachable; // 丢弃中
        const user_len = dw.count + dw.writer.end;

        dw.count = 0;
        dw.writer.end = 0;
        password.formatPassword(&dw.writer) catch unreachable; // 丢弃中
        const password_len = dw.count + dw.writer.end;

        return valueLength(@intCast(user_len), @intCast(password_len));
    }

    pub fn value(uri: Uri, out: []u8) []u8 {
        var bw: Writer = .fixed(out);
        write(uri, &bw) catch unreachable;
        return bw.buffered();
    }

    pub fn write(uri: Uri, out: *Writer) Writer.Error!void {
        var buf: [max_user_len + 1 + max_password_len]u8 = undefined;
        var w: Writer = .fixed(&buf);
        const user: Uri.Component = uri.user orelse .empty;
        const password: Uri.Component = uri.password orelse .empty;
        user.formatUser(&w) catch unreachable;
        w.writeByte(':') catch unreachable;
        password.formatPassword(&w) catch unreachable;
        try out.print("Basic {b64}", .{w.buffered()});
    }
};

pub const ConnectTcpError = error{
    TlsInitializationFailed,
} || Allocator.Error || HostName.ConnectError || Io.Cancelable;

/// 若已有匹配 `host` 和 `port` 的连接处于打开状态,则复用该 `Connection`。
///
/// 线程安全。
pub fn connectTcp(
    client: *Client,
    host: HostName,
    port: u16,
    protocol: Protocol,
) ConnectTcpError!*Connection {
    return connectTcpOptions(client, .{ .host = host, .port = port, .protocol = protocol });
}

pub const ConnectTcpOptions = struct {
    host: HostName,
    port: u16,
    protocol: Protocol,

    proxied_host: ?HostName = null,
    proxied_port: ?u16 = null,
    timeout: Io.Timeout = .none,
};

pub fn connectTcpOptions(client: *Client, options: ConnectTcpOptions) ConnectTcpError!*Connection {
    const io = client.io;
    const host = options.host;
    const port = options.port;
    const protocol = options.protocol;

    const proxied_host = options.proxied_host orelse host;
    const proxied_port = options.proxied_port orelse port;

    if (try client.connection_pool.findConnection(io, .{
        .host = proxied_host,
        .port = proxied_port,
        .protocol = protocol,
    })) |conn| return conn;

    var stream = try host.connect(io, port, .{ .mode = .stream });
    errdefer stream.close(io);

    switch (protocol) {
        .tls => {
            if (disable_tls) return error.TlsInitializationFailed;
            const tc = Connection.Tls.create(client, proxied_host, proxied_port, stream) catch |err| switch (err) {
                error.OutOfMemory => |e| return e,
                error.Unexpected => |e| return e,
                error.Canceled => |e| return e,
                else => return error.TlsInitializationFailed,
            };
            errdefer tc.destroy();
            try client.connection_pool.addUsed(io, &tc.connection);
            return &tc.connection;
        },
        .plain => {
            const pc = try Connection.Plain.create(client, proxied_host, proxied_port, stream);
            errdefer pc.destroy();
            try client.connection_pool.addUsed(io, &pc.connection);
            return &pc.connection;
        },
    }
}

pub const ConnectUnixError = Allocator.Error || std.posix.SocketError || error{NameTooLong} || std.posix.ConnectError || Io.Cancelable;

/// 将 `path` 作为 Unix 域套接字连接。若已有打开连接,则复用它。
///
/// 此函数线程安全。
pub fn connectUnix(client: *Client, path: []const u8) ConnectUnixError!*Connection {
    const io = client.io;

    if (try client.connection_pool.findConnection(io, .{
        .host = path,
        .port = 0,
        .protocol = .plain,
    })) |node|
        return node;

    const conn = try client.allocator.create(ConnectionPool.Node);
    errdefer client.allocator.destroy(conn);
    conn.* = .{ .data = undefined };

    const stream = try Io.net.connectUnixSocket(path);
    errdefer stream.close(io);

    conn.data = .{
        .stream = stream,
        .tls_client = undefined,
        .protocol = .plain,

        .host = try client.allocator.dupe(u8, path),
        .port = 0,
    };
    errdefer client.allocator.free(conn.data.host);

    try client.connection_pool.addUsed(conn);

    return &conn.data;
}

/// 通过指定代理,使用 HTTP CONNECT 连接到
/// `proxied_host:proxied_port`。若已有打开的连接,则复用它。
///
/// 此函数是线程安全的。
pub fn connectProxied(
    client: *Client,
    proxy: *Proxy,
    proxied_host: HostName,
    proxied_port: u16,
) !*Connection {
    const io = client.io;
    if (!proxy.supports_connect) return error.TunnelNotSupported;

    if (try client.connection_pool.findConnection(io, .{
        .host = proxied_host,
        .port = proxied_port,
        .protocol = proxy.protocol,
    })) |node| return node;

    var maybe_valid = false;
    (tunnel: {
        const connection = try client.connectTcpOptions(.{
            .host = proxy.host,
            .port = proxy.port,
            .protocol = proxy.protocol,
            .proxied_host = proxied_host,
            .proxied_port = proxied_port,
        });
        errdefer {
            connection.closing = true;
            client.connection_pool.release(connection, io);
        }

        var req = client.request(.CONNECT, .{
            .scheme = "http",
            .host = .{ .raw = proxied_host.bytes },
            .port = proxied_port,
        }, .{
            .redirect_behavior = .unhandled,
            .connection = connection,
        }) catch |err| {
            break :tunnel err;
        };
        defer req.deinit();

        req.sendBodiless() catch |err| break :tunnel err;
        const response = req.receiveHead(&.{}) catch |err| break :tunnel err;

        if (response.head.status.class() == .server_error) {
            maybe_valid = true;
            break :tunnel error.ServerError;
        }

        if (response.head.status != .ok) break :tunnel error.ConnectionRefused;

        // 此连接现已成为隧道,无法再用于其他用途,
        // 仅在客户端反初始化时才会释放。
        req.connection = null;

        connection.closing = false;

        return connection;
    }) catch {
        // 隧道出现错误
        proxy.supports_connect = maybe_valid;
        return error.TunnelNotSupported;
    };
}

pub const ConnectError = ConnectTcpError || RequestError;

/// 使用指定协议连接到 `host:port`。若已有
/// 打开的连接,则复用该连接。
///
/// 若客户端配置了代理,则通过代理
/// 连接主机。
///
/// 此函数是线程安全的。
pub fn connect(
    client: *Client,
    host: HostName,
    port: u16,
    protocol: Protocol,
) ConnectError!*Connection {
    const proxy = switch (protocol) {
        .plain => client.http_proxy,
        .tls => client.https_proxy,
    } orelse return client.connectTcp(host, port, protocol);

    // 防止通过自身进行代理。
    if (proxy.host.eql(host) and proxy.port == port and proxy.protocol == protocol) {
        return client.connectTcp(host, port, protocol);
    }

    if (proxy.supports_connect) tunnel: {
        return connectProxied(client, proxy, host, port) catch |err| switch (err) {
            error.TunnelNotSupported => break :tunnel,
            else => |e| return e,
        };
    }

    // 回退为将代理作为普通 http 代理使用
    const connection = try client.connectTcp(proxy.host, proxy.port, proxy.protocol);
    connection.proxied = true;
    return connection;
}

pub const RequestError = ConnectTcpError || error{
    UnsupportedUriScheme,
    UriMissingHost,
    InvalidHostName,
    CertificateBundleLoadFailure,
};

pub const RequestOptions = struct {
    version: http.Version = .@"HTTP/1.1",

    /// 自动忽略 100 Continue 响应。假定调用者不关心该响应,会在等待响应之前发送请求体。
    ///
    /// 若并非如此,且已知服务器会发送 100 Continue,则将此选项设为 false,在发送请求体之前等待响应。
    /// 若选择等待,但服务器在请求完成之前不发送 100 Continue,则该请求必然死锁。
    ///
    ///
    ///
    handle_continue: bool = true,

    /// 若为 false,则在这一次请求后关闭连接;若为 true,
    /// 则加入客户端连接池。
    keep_alive: bool = true,

    /// 此字段指定是否自动跟随重定向,
    /// 以及在返回错误之前最多跟随多少次重定向。
    ///
    /// 仅对可重复的请求跟随重定向,即没有
    /// 负载,或服务器已确认负载的请求。
    redirect_behavior: Request.RedirectBehavior = @fromBackingInt(@intCast(3)),

    /// 必须是已获取的连接。
    connection: ?*Connection = null,

    /// 具有默认行为且允许覆盖该行为的标准头字段。
    headers: Request.Headers = .{},
    /// 即使跟随重定向至其他域名,也会保留
    /// 这些头部。
    /// 所有权属于外部;必须比 Request 存活更久。
    extra_headers: []const http.Header = &.{},
    /// 跟随重定向到其他域时会移除这些头字段。
    /// 所有权属于外部;生存期必须长于 Request。
    ///
    privileged_headers: []const http.Header = &.{},
};

fn uriPort(uri: Uri, protocol: Protocol) u16 {
    return uri.port orelse protocol.port();
}

/// 打开到 `uri` 指定主机的连接,并准备发送 HTTP 请求。
///
/// 调用者负责对 `Request` 调用 `deinit()`。
/// 此函数是线程安全的。
///
/// 断言任何头字段的名称或值中都不含 "\r\n"。
pub fn request(
    client: *Client,
    method: http.Method,
    uri: Uri,
    options: RequestOptions,
) RequestError!Request {
    const io = client.io;

    if (std.debug.runtime_safety) {
        for (options.extra_headers) |header| {
            assert(header.name.len != 0);
            assert(std.mem.findScalar(u8, header.name, ':') == null);
            assert(std.mem.findPosLinear(u8, header.name, 0, "\r\n") == null);
            assert(std.mem.findPosLinear(u8, header.value, 0, "\r\n") == null);
        }
        for (options.privileged_headers) |header| {
            assert(header.name.len != 0);
            assert(std.mem.findPosLinear(u8, header.name, 0, "\r\n") == null);
            assert(std.mem.findPosLinear(u8, header.value, 0, "\r\n") == null);
        }
    }

    const protocol = Protocol.fromUri(uri) orelse return error.UnsupportedUriScheme;

    if (protocol == .tls) tls: {
        if (disable_tls) unreachable;
        {
            try client.ca_bundle_lock.lockShared(io);
            defer client.ca_bundle_lock.unlockShared(io);
            if (client.now != null) break :tls;
        }
        var bundle: std.crypto.Certificate.Bundle = .empty;
        defer bundle.deinit(client.allocator);
        const now = Io.Clock.real.now(io);
        bundle.rescan(client.allocator, io, now) catch |err| switch (err) {
            error.Canceled => |e| return e,
            else => return error.CertificateBundleLoadFailure,
        };
        try client.ca_bundle_lock.lock(io);
        defer client.ca_bundle_lock.unlock(io);
        client.now = now;
        std.mem.swap(std.crypto.Certificate.Bundle, &client.ca_bundle, &bundle);
    }

    const connection = options.connection orelse c: {
        var host_name_buffer: [HostName.max_len]u8 = undefined;
        const host_name = HostName.fromUri(uri, &host_name_buffer) catch |err| switch (err) {
            error.UriMissingHost => |e| return e,
            error.NameTooLong, error.InvalidHostName => return error.InvalidHostName,
        };
        break :c try client.connect(host_name, uriPort(uri, protocol), protocol);
    };

    return .{
        .uri = uri,
        .client = client,
        .connection = connection,
        .reader = .{
            .in = connection.reader(),
            .state = .ready,
            // 调用 `http.Reader.bodyReader` 时填充。
            .interface = undefined,
            .max_head_len = client.read_buffer_size,
            .side = .response,
        },
        .keep_alive = options.keep_alive,
        .method = method,
        .version = options.version,
        .transfer_encoding = .none,
        .redirect_behavior = options.redirect_behavior,
        .handle_continue = options.handle_continue,
        .headers = options.headers,
        .extra_headers = options.extra_headers,
        .privileged_headers = options.privileged_headers,
    };
}

pub const FetchOptions = struct {
    /// `null` 表示将在堆上分配。RFC 9110 建议至少使用 8000 字节。
    ///
    redirect_buffer: ?[]u8 = null,
    /// `null` 表示将在堆上分配。
    decompress_buffer: ?[]u8 = null,
    redirect_behavior: ?Request.RedirectBehavior = null,
    /// 如果服务器发送消息体,则将其写入此处。
    response_writer: ?*Writer = null,

    location: Location,
    method: ?http.Method = null,
    payload: ?[]const u8 = null,
    raw_uri: bool = false,
    keep_alive: bool = true,

    /// 具有默认行为且允许覆盖该行为的标准头字段。
    headers: Request.Headers = .{},
    /// 即使跟随重定向至其他域名,也会保留
    /// 这些头部。
    /// 所有权属于外部;必须比 Request 存活更久。
    extra_headers: []const http.Header = &.{},
    /// 跟随重定向到其他域时会移除这些头字段。
    /// 所有权属于外部;生存期必须长于 Request。
    ///
    privileged_headers: []const http.Header = &.{},

    pub const Location = union(enum) {
        url: []const u8,
        uri: Uri,
    };
};

pub const FetchResult = struct {
    status: http.Status,
};

pub const FetchError = Uri.ParseError || RequestError || Request.ReceiveHeadError || error{
    StreamTooLong,
    /// TODO: 遇到此情况时提供可选诊断信息,或拆分为更多错误码
    WriteFailed,
    UnsupportedCompressionMethod,
};

/// 使用给定选项执行一次性 HTTP 请求。
///
/// 此函数是线程安全的。
pub fn fetch(client: *Client, options: FetchOptions) FetchError!FetchResult {
    const uri = switch (options.location) {
        .url => |u| try Uri.parse(u),
        .uri => |u| u,
    };
    const method: http.Method = options.method orelse
        if (options.payload != null) .POST else .GET;

    const redirect_behavior: Request.RedirectBehavior = options.redirect_behavior orelse
        if (options.payload == null) @fromBackingInt(@intCast(3)) else .unhandled;

    var req = try request(client, method, uri, .{
        .redirect_behavior = redirect_behavior,
        .headers = options.headers,
        .extra_headers = options.extra_headers,
        .privileged_headers = options.privileged_headers,
        .keep_alive = options.keep_alive,
    });
    defer req.deinit();

    if (options.payload) |payload| {
        req.transfer_encoding = .{ .content_length = payload.len };
        var body = try req.sendBodyUnflushed(&.{});
        try body.writer.writeAll(payload);
        try body.end();
        try req.connection.?.flush();
    } else {
        try req.sendBodiless();
    }

    const redirect_buffer: []u8 = if (redirect_behavior == .unhandled) &.{} else options.redirect_buffer orelse
        try client.allocator.alloc(u8, 8 * 1024);
    defer if (options.redirect_buffer == null) client.allocator.free(redirect_buffer);

    var response = try req.receiveHead(redirect_buffer);

    const response_writer = options.response_writer orelse {
        const reader = response.reader(&.{});
        _ = reader.discardRemaining() catch |err| switch (err) {
            error.ReadFailed => return response.bodyErr().?,
        };
        return .{ .status = response.head.status };
    };

    const decompress_buffer: []u8 = switch (response.head.content_encoding) {
        .identity => &.{},
        .zstd => options.decompress_buffer orelse try client.allocator.alloc(u8, std.compress.zstd.default_window_len),
        .deflate, .gzip => options.decompress_buffer orelse try client.allocator.alloc(u8, std.compress.flate.max_window_len),
        .compress => return error.UnsupportedCompressionMethod,
    };
    defer if (options.decompress_buffer == null) client.allocator.free(decompress_buffer);

    var transfer_buffer: [64]u8 = undefined;
    var decompress: http.Decompress = undefined;
    const reader = response.readerDecompressing(&transfer_buffer, &decompress, decompress_buffer);

    _ = reader.streamRemaining(response_writer) catch |err| switch (err) {
        error.ReadFailed => return response.bodyErr().?,
        else => |e| return e,
    };

    return .{ .status = response.head.status };
}

test {
    _ = Response;
}