Lyricdev
GitHub

std.http

Speaks HTTP/1.1 (RFC 9110, RFC 9112) over Reader and Writer: the message types, a client and a server.

The message types are Method, Status, Headers, Request, Response and Body; the errors are HttpError beside the I/O errors. The client: Client.send writes a request over a connection it keeps alive for the next one to the same authority, reads the status line and the headers, and hands the body back as a Reader that knows its length (Content-Length), its chunks (Transfer-Encoding: chunked) or its end (the connection's close). Redirects are followed where asked, a timeout spans the whole exchange, and the transport hook of the options makes the connection — TCP here, TLS where a package puts its own Stream into it. The server: Server.bind(addr).serve(handler) takes a task per connection, reads each request as the client writes one (its body a Reader the handler may read or leave), answers Expect: 100-continue, writes the handler's Response with its length or in chunks, keeps the connection for the next request, and ends with shutdown(). The module has no TLS of its own, no HTTP/2 and no cookies.

Examples

Compiles; not run here

import std.io { println };
import std.http;

fn main(): void throws Error {
    let response = try http.get("http://example.com/");
    println(response.status);
    println(try response.text());
}

Types

HttpError struct — The error the client throws beyond the I/O errors of the connection.
Method enum — A request's method; Other for a token beyond the common ones.
Status struct — A status: the code and its reason phrase.
Headers class — The header fields of a message, in the order written; names compare without case.
Request struct — A request: the method, the URI, the headers, and a body — a Reader with its length where known (Content-Length), sent in chunks otherwise.
Response class — A response: the status, the headers, the body as a Reader that ends where the message does.
Stream interface — A connection a transport gives: read, written and closed.
Body class — A message's body as a Reader: the bytes up to the message's end, however it is framed.
ClientOptions struct — The options of a Client.
Client class
ServerOptions struct — The options of a Server.
Server class — An HTTP/1.1 server over a TcpListener: serve runs until shutdown.

Functions

pub fn reasonOf(code: int): string

Returns the reason phrase RFC 9110 §15 gives a status code, or an empty string for a code without one here.

pub fn get(uri: string): Response throws [HttpError, IoError, TimedOut, Cancelled, ParseError]

Sends a GET of the URI's text with a client of the default options, redirects followed.

Errors

Throws ParseError for a text that is no URI, and otherwise as Client.send does.

Extensions

extend TcpStream :: [Stream]

Conforms to Stream.