std.http: add missing documentation and a few examples

This commit is contained in:
Nameless
2023-12-14 15:52:39 -06:00
committed by Andrew Kelley
parent 832f6d8f7f
commit b723296e1f
4 changed files with 141 additions and 13 deletions

View File

@@ -1,4 +1,8 @@
//! Connecting and opening requests are threadsafe. Individual requests are not.
//! HTTP(S) Client implementation.
//!
//! Connections are opened in a thread-safe manner, but individual Requests are not.
//!
//! TLS support may be disabled via `std.options.http_disable_tls`.
const std = @import("../std.zig");
const builtin = @import("builtin");
@@ -157,6 +161,9 @@ pub const ConnectionPool = struct {
pool.free_size = new_size;
}
/// Frees the connection pool and closes all connections within. This function is threadsafe.
///
/// All future operations on the connection pool will deadlock.
pub fn deinit(pool: *ConnectionPool, allocator: Allocator) void {
pool.mutex.lock();
@@ -191,11 +198,19 @@ pub const Connection = struct {
/// undefined unless protocol is tls.
tls_client: if (!disable_tls) *std.crypto.tls.Client else void,
/// The protocol that this connection is using.
protocol: Protocol,
/// The host that this connection is connected to.
host: []u8,
/// The port that this connection is connected to.
port: u16,
/// Whether this connection is proxied and is not directly connected.
proxied: bool = false,
/// Whether this connection is closing when we're done with it.
closing: bool = false,
read_start: BufferSize = 0,
@@ -232,6 +247,7 @@ pub const Connection = struct {
};
}
/// Refills the read buffer with data from the connection.
pub fn fill(conn: *Connection) ReadError!void {
if (conn.read_end != conn.read_start) return;
@@ -244,14 +260,17 @@ pub const Connection = struct {
conn.read_end = @intCast(nread);
}
/// Returns the current slice of buffered data.
pub fn peek(conn: *Connection) []const u8 {
return conn.read_buf[conn.read_start..conn.read_end];
}
/// Discards the given number of bytes from the read buffer.
pub fn drop(conn: *Connection, num: BufferSize) void {
conn.read_start += num;
}
/// Reads data from the connection into the given buffer.
pub fn read(conn: *Connection, buffer: []u8) ReadError!usize {
const available_read = conn.read_end - conn.read_start;
const available_buffer = buffer.len;
@@ -318,6 +337,7 @@ pub const Connection = struct {
};
}
/// Writes the given buffer to the connection.
pub fn write(conn: *Connection, buffer: []const u8) WriteError!usize {
if (conn.write_end + buffer.len > conn.write_buf.len) {
try conn.flush();
@@ -334,6 +354,7 @@ pub const Connection = struct {
return buffer.len;
}
/// Flushes the write buffer to the connection.
pub fn flush(conn: *Connection) WriteError!void {
if (conn.write_end == 0) return;
@@ -352,6 +373,7 @@ pub const Connection = struct {
return Writer{ .context = conn };
}
/// Closes the connection.
pub fn close(conn: *Connection, allocator: Allocator) void {
if (conn.protocol == .tls) {
if (disable_tls) unreachable;
@@ -502,8 +524,13 @@ pub const Response = struct {
try expectEqual(@as(u10, 999), parseInt3("999"));
}
/// The HTTP version this response is using.
version: http.Version,
/// The status code of the response.
status: http.Status,
/// The reason phrase of the response.
reason: []const u8,
/// If present, the number of bytes in the response body.
@@ -528,22 +555,36 @@ pub const Response = struct {
///
/// Order of operations: open -> send[ -> write -> finish] -> wait -> read
pub const Request = struct {
/// The uri that this request is being sent to.
uri: Uri,
/// The client that this request was created from.
client: *Client,
/// is null when this connection is released
/// Underlying connection to the server. This is null when the connection is released.
connection: ?*Connection,
method: http.Method,
version: http.Version = .@"HTTP/1.1",
/// The list of HTTP request headers.
headers: http.Headers,
/// The transfer encoding of the request body.
transfer_encoding: RequestTransfer = .none,
/// The redirect quota left for this request.
redirects_left: u32,
/// Whether the request should follow redirects.
handle_redirects: bool,
/// Whether the request should handle a 100-continue response before sending the request body.
handle_continue: bool,
/// The response associated with this request.
///
/// This field is undefined until `wait` is called.
response: Response,
/// Used as a allocator for resolving redirects locations.
@@ -993,6 +1034,7 @@ pub const Request = struct {
}
};
/// A HTTP proxy server.
pub const Proxy = struct {
allocator: Allocator,
headers: http.Headers,
@@ -1144,6 +1186,7 @@ pub fn loadDefaultProxies(client: *Client) !void {
pub const ConnectTcpError = Allocator.Error || error{ ConnectionRefused, NetworkUnreachable, ConnectionTimedOut, ConnectionResetByPeer, TemporaryNameServerFailure, NameServerFailure, UnknownHostName, HostLacksNetworkAddresses, UnexpectedConnectFailure, TlsInitializationFailed };
/// Connect to `host:port` using the specified protocol. This will reuse a connection if one is already open.
///
/// This function is threadsafe.
pub fn connectTcp(client: *Client, host: []const u8, port: u16, protocol: Connection.Protocol) ConnectTcpError!*Connection {
if (client.connection_pool.findConnection(.{
@@ -1203,6 +1246,7 @@ pub fn connectTcp(client: *Client, host: []const u8, port: u16, protocol: Connec
pub const ConnectUnixError = Allocator.Error || std.os.SocketError || error{ NameTooLong, Unsupported } || std.os.ConnectError;
/// Connect to `path` as a unix domain socket. This will reuse a connection if one is already open.
///
/// This function is threadsafe.
pub fn connectUnix(client: *Client, path: []const u8) ConnectUnixError!*Connection {
if (!net.has_unix_sockets) return error.Unsupported;
@@ -1237,6 +1281,7 @@ pub fn connectUnix(client: *Client, path: []const u8) ConnectUnixError!*Connecti
}
/// Connect to `tunnel_host:tunnel_port` using the specified proxy with HTTP CONNECT. This will reuse a connection if one is already open.
///
/// This function is threadsafe.
pub fn connectTunnel(
client: *Client,
@@ -1318,7 +1363,6 @@ const ConnectErrorPartial = ConnectTcpError || error{ UnsupportedUrlScheme, Conn
pub const ConnectError = ConnectErrorPartial || RequestError;
/// Connect to `host:port` using the specified protocol. This will reuse a connection if one is already open.
///
/// If a proxy is configured for the client, then the proxy will be used to connect to the host.
///
/// This function is threadsafe.
@@ -1375,7 +1419,10 @@ pub const RequestOptions = struct {
/// request, then the request *will* deadlock.
handle_continue: bool = true,
/// Automatically follow redirects. This will only follow redirects for repeatable requests (ie. with no payload or the server has acknowledged the payload)
handle_redirects: bool = true,
/// How many redirects to follow before returning an error.
max_redirects: u32 = 3,
header_strategy: StorageStrategy = .{ .dynamic = 16 * 1024 },