Skip to content

std.http

HTTP/1.1 requests and responses, a client (send, fetch, TLS for https://) and a server (serve, a Router), over any std.net.Stream. A handler is a function (Request) -> Response, which tests call directly; the wire functions take a Stream, so tests pass a mock connection.

type Pattern = String
where matches(it, "/[-a-zA-Z0-9_.~:/]*")

A path whose segments may be names: /users/:id.

type Router = { routes: List[Route] }

Routes, tried in the order they were added. Dispatch is a linear scan.

type Request = {
method: Method,
/// The path without the query, as sent: percent escapes stay
/// (`/files/a%2Fb`), so a `/` inside a part is told apart from one
/// between parts. `Router` decodes each part after splitting.
path: String,
/// The decoded query parameters: `?sort=year` is `{"sort": "year"}`.
query: Dict[String, String],
/// Header names are lowercase. Read them with `header` or `header_values`.
headers: Headers,
/// The body as UTF-8 text.
body: String,
/// The path parts its route named (`:id` in `/users/:id`), decoded, set by `Router.handle`.
params: Dict[String, String],
}

A request as the server read it (read_request), handed to a handler.

type Method = String
where matches(it, "GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS")

An HTTP method in capitals: GET, POST, ….

type Response = { status: Status, headers: Headers, body: String }

A response. The server refuses header values that hold line breaks.

type Status = Int
where 100 <= it && it <= 599

An HTTP status code.

type HttpError = NetError | BadMessage | BadUrl

Why an HTTP exchange failed: the network’s error, a message that isn’t the HTTP/1.1 this module reads, or a URL it can’t use.

type BadMessage = { message: String }

What arrived isn’t HTTP/1.1 as this module reads it, or passes a limit.

type BadUrl = { url: String, message: String }

A URL send can’t use.

type Url = { tls: Bool, host: String, port: Port, target: String }

A URL split for a request: https://api.example.com:8443/v1/x?y=1 is TLS to api.example.com on 8443, asking for /v1/x?y=1.

type Streaming = { status: Status, headers: Headers, body: Body }

A response whose body is still arriving: its status and headers, and the body to read from the open connection. Made by open.

type Body = {
conn: TcpStream,
chunked: Bool,
/// Bytes left: of the `content-length`, or of the current chunk. -1: up
/// to the end of the stream.
left: Int,
/// Bytes read from the connection; those before `start` were given out.
pending: List[Int] = [],
/// Where the bytes not yet given out start in `pending`.
start: Natural = 0,
/// `pending` holds no `\n` from `start` up to here.
scanned: Natural = 0,
ended: Bool = false,
}

A response’s body read from its connection as it arrives, by content-length, by chunks, or up to the end of the stream. Close it when done (Body.close).

type Headers = List[(String, String)]

Header fields, in order: a name given twice (two set-cookies) is there twice.

type ServerLimits = {
/// Connections open at once. More wait in the listener's backlog.
connections: Positive,
/// The longest wait for the next request on a connection, read whole.
read: Duration,
/// The longest wait to send a response.
write: Duration,
}

How long serve waits on a connection, and how many connections it keeps open.

fn param(self, name: String) -> Option[String]

The path part the route named name: req.param("id") for /users/:id. None if the route has no such part or the request didn’t come through a Router.

fn new() -> Router

A router with no routes.

fn on(
mut self,
method: Method,
pattern: Pattern,
handler: (Request) -> Response,
)

Sends method requests whose path fits pattern to handler.

fn get(mut self, pattern: Pattern, handler: (Request) -> Response)
fn post(mut self, pattern: Pattern, handler: (Request) -> Response)
fn put(mut self, pattern: Pattern, handler: (Request) -> Response)
fn patch(mut self, pattern: Pattern, handler: (Request) -> Response)
fn delete(mut self, pattern: Pattern, handler: (Request) -> Response)
fn handle(self, req: Request) -> Response

The response of the first route that fits, with the named path parts in req.params.

  • A HEAD request uses the GET routes.
  • No route for the path gives 404. Routes for it, but not for this method, give 405.
fn read_line(mut self) -> Result[Option[String], HttpError]

The next line of the body, without its \n or \r\n: None at its end. A line longer than line_limit() is an error.

fn rest(mut self) -> Result[String, HttpError]

The rest of the body, as text.

fn more(mut self) -> Result[Bool, HttpError]

Reads more of the body into pending: false at its end.

fn close(mut self)

Closes the connection.

fn get_request(path: String) -> Request

A GET request for path with no query, headers or body, for tests.

fn ok_html(body: String) -> Response

200 with an HTML page, such as std.web.document makes.

fn respond(status: Status, content_type: String, body: String) -> Response

A response with this status, content type and body.

fn ok_text(body: String) -> Response

200 with plain text.

fn ok_json[T: Json](value: T) -> Response

200 with value as JSON. 500 with the message when it has no JSON form, such as an integer beyond what a JSON number holds exactly.

fn redirect(location: String) -> Response

303: the browser goes to location with a GET. Used after a form is posted, so reloading doesn’t post it again.

fn match_path(pattern: String, path: String) -> Option[Dict[String, String]]

The names pattern gives to the parts of path, if it fits. path is split at /, then each part is decoded (percent_decode), so /files/a%2Fb fits /files/:name with name a/b.

fn method_not_allowed() -> Response

405: the path exists, but not for this method.

fn not_found() -> Response
fn fetch(net: Net, url: String) -> Result[Response, HttpError]

GET url.

fn send(
net: Net,
method: Method,
url: String,
headers: List[(String, String)],
body: String,
) -> Result[Response, HttpError]

Sends a request and reads the response, on a connection of its own (TLS for https://), closed after. Sends content-length, host and connection: close besides headers.

fn parse_url(url: String) -> Result[Url, BadUrl]

http:// or https://, a host, maybe :port, then the target (/ when there is none). A host or target holding a space, a control character or a byte past ASCII is an error: it would break the request line or the host header.

fn exchange(
mut conn: Stream,
method: Method,
host: String,
target: String,
headers: List[(String, String)],
body: String,
) -> Result[Response, HttpError]

Writes a request on conn and reads its response: any Stream, so a test passes a mock. The request asks the server to close after.

fn read_response(
mut conn: Stream,
method: Method,
) -> Result[Response, HttpError]

A response as the server sent it to a method request: the status line, the headers (lowercase names, each as it came), the body by content-length, chunks, or up to the end of the stream. A response to HEAD, a 1xx, 204 or 304 has no body.

fn line_limit() -> Natural

The longest request or status line and header line read: 16 KB.

fn body_limit() -> Natural

The largest body read: 64 MB.

fn serve(
listener: Listener,
handler: (Request) -> Response,
clock: Clock,
) -> NetError

serve_limited with server_limits().

fn serve_connection(
mut conn: Stream,
handler: (Request) -> Response,
clock: Clock,
limits: ServerLimits,
) -> Result[Natural, NetError]

Answers the requests on one connection with handler until the client closes it or asks to (connection: close), then closes it. Returns how many requests were answered.

  • A request it can’t read gets a 400 and ends the connection.
  • A request not read whole within limits.read ends the connection, as

a response not sent within limits.write does.

  • Each request is handled in a supervised task, a thread of its own: a

handler that panics gets the request a 500 and ends the connection.

  • A HEAD request gets the head of the response, with the

content-length of its body.

fn read_request(mut conn: Stream) -> Result[Option[Request], HttpError]

The next request on conn: None if the client closed first. A path with a . or .. part, as sent or once decoded, is an error.

fn percent_decode(s: String, plus: Bool) -> String

%20 as a space, and + too when plus (a query). An escape that isn’t two hexadecimal digits, or bytes that aren’t UTF-8, stay as written.

fn parse_query(query: String) -> Dict[String, String]

a=1&b=x%20y as {"a": "1", "b": "x y"}. A + is a space. A name given twice keeps its last value.

fn write_response(mut conn: Stream, r: Response) -> Result[(), NetError]

Writes r with its content-length. A header holding a line break is left out.

fn open(
net: Net,
method: Method,
url: String,
headers: List[(String, String)],
body: String,
) -> Result[Streaming, HttpError]

Sends a request and reads the response’s status and headers, leaving its body to be read as it arrives: for server-sent events and other long responses. TLS for https://. The connection is the body’s.

fn header_values(headers: Headers, name: String) -> List[String]

The values of the header name, in any case, in order.

fn header(headers: Headers, name: String) -> Option[String]

The header name, in any case: its values joined by , when it is given more than once (RFC 9110 5.3). None when it isn’t there. A set-cookie can’t be joined so: read it with header_values.

fn visible(s: String) -> Bool

Whether s is printable ASCII without spaces, and not empty: what a request line’s target and the host header may hold.

fn write_head(mut conn: Stream, r: Response) -> Result[(), NetError]

Writes the head of r alone, with the content-length of its body: the answer to a HEAD request.

fn server_limits() -> ServerLimits

256 connections, 30 seconds to read a request and 30 to send a response.

fn serve_limited(
listener: Listener,
handler: (Request) -> Response,
clock: Clock,
limits: ServerLimits,
) -> NetError

Accepts connections on listener and answers each in a task of its own (serve_connection), until the listener is closed or the task is cancelled. Returns why it stopped. At most limits.connections are open at once: the next waits in the backlog until one closes. An accept the system refuses (no file descriptors left, say) is skipped after a pause of 10 ms, and the connection waits in the backlog.