OxL Reference

module std.http

std.http — HTTP client (HTTP/1.1, HTTP/2), server, router, SSE and WebSocket (II.1 std.http, [С ч. II], D-3920..D-3971). Every client request has the effect net.

oxl
use std.http { Client as Http, HttpConfig }

let r = Http.get("http://example.org/ping")?
if r.ok() { print(r.text()!) }
let p = Http.postText("https://api.example.org/items", "{\"n\":1}", [Header{ name: "Content-Type", value: "application/json" }],
                      HttpConfig{ timeout: 5s })?
  • Requests are made through the static functions of Client (Http.get(url)); the connection pool is process-wide, so tasks share keep-alive connections without sharing a value. A status of 4xx/5xx is a normal Response, not an error.
  • Errors are NetError values like in std.net (§6.5, D-2203): Timeout (the whole request, including redirects, did not finish within HttpConfig.timeout), Unavailable (refused, reset, unreachable, name not found), AccessDenied, Cancelled, and ProtocolError for everything else; its msg starts with http: (bad URL or header, malformed response, body above maxBody, too many redirects) or tls.
  • Waits park only the calling task and are cancellation points; a cancelled task (or one whose chain deadline passed) leaves the request at once and its connection is closed.
  • HTTP/1.1 for http://; https:// offers HTTP/2 in ALPN and uses it when the server selects it (D-3997; HttpConfig.http2). HTTP/1.1: Content-Length, chunked (response bodies always, request bodies with HttpConfig.chunkedUpload) and close-delimited bodies; keep-alive with a pool (8 idle connections per origin, 30 s); a pooled connection that turns out dead is replaced transparently for idempotent methods; redirects (301/302/303/307/308, maxRedirects, default 5; credentials are not sent to another origin; https to http is refused). https:// verifies the certificate against the system roots or ca.
  • Response bodies are read completely (maxBody, default 64 MiB; Client.openStream reads them piece by piece, D-3970); compressed content is not requested or decoded. Intrinsics: runtime/src/http1/http1.cpp.

Example:

oxl✓ checked in CI
use std.http { Server, ServerConfig, Router, Request, Reply, Client }

fn run() -> () | NetError | DecodeError | Panicked  net, io, time {
  let srv = Server.bind(ServerConfig{ port: 0, followNode: false })?
  defer srv.close()
  let stop = srv.handle()
  let router = Router.new().get("/hello/:name", (req: Request) => Reply.text("hi {req.param("name") ?? "?"}"))
  let base = "http://127.0.0.1:{srv.port()}"
  scope {
    spawn stop.serve(router)
    let r = Client.get("{base}/hello/Ann")?
    print("{r.status} {r.text()?}")
    stop.shutdown()
    ()
  }?
}

fn main() io, net, time {
  match run() {
    NetError _ => print("net error")
    DecodeError _ => print("decode error")
    Panicked _ => print("panicked")
    _ => {}
  }
}
Output
200 hi Ann

Types

data BodyReaderA body read piece by piece
data BodyWriterWriter of a streamed response body (Reply.stream).
data ClientThe namespace of the client functions
data HeaderOne header field.
data Http2An HTTP/2 connection to one origin (RFC 9113).
data Http2HandleA copyable reference to an Http2 connection for other tasks (Http2.handle())
data HttpConfigSettings of a request.
type MiddlewareWraps a request
type NextThe rest of the chain as seen by a middleware
data ReplyThe answer of a handler.
data RequestA request received by a Server.
data ResponseAn HTTP response.
data ResponseStreamA response whose head has arrived and whose body is read piece by piece (D-3970)
data RouterRoutes by method and path pattern.
data ServerAn HTTP/1.1 server (II.1 std.http)
data ServerConfigSettings of a Server.
data ServerHandleA copyable token that can stop a server from a handler or another task (Server.handle()).
data SseConfigSettings of SseStream.open.
data SseEventOne event received from an event stream.
data SseStreamThe reading side of a server-sent events connection (text/event-stream).
data SseWriterWriter of a server-sent events stream (Reply.sse).
data WebSocketAn open WebSocket (RFC 6455), made by WebSocket.connect (client) or handed to the function of Reply.websocket (server).
data WsConfigSettings of WebSocket.connect.
enum WsKindKind of a WebSocket message.
data WsMessageA message received on a WebSocket.

Functions

chunksThe body of a request as a stream of pieces
logRequestsLogs METHOD path -> status (N ms) on stderr for every request.
requireHeaderAnswers status (default 401) without calling the handler unless the request has header name (equal to value, when value is not empty)
timingAdds Server-Timing
withMiddlewarehandler wrapped in mw

See also