@std/net/http.ms#
Import each required symbol with import Name from "@std/net/http.ms".
ClientResponse Type#
Buffered response body with explicit common metadata access.
type ClientResponse {
head HttpResponseMetadata
body Bytes
}ClientResponse.body#
The complete response payload within the supplied byte bound.
body BytesClientResponse.head#
Response metadata; changing it requires a mutable response and no live borrow of head.
head HttpResponseMetadataClientResponse.metadata#
Returns an independent copy of the response metadata, including its headers.
fn metadata() HttpResponseMetadataHttpClient Type#
Reusable HTTP client with connection pooling and explicit response limits. Outbound headers retain separate values in their stored order.
type HttpClient {
native NativeHttpClient
}HttpClient.native#
The runtime handle; it is released by close and owned by this value.
native NativeHttpClientHttpClient.close#
Cancels in-flight requests, closes open response bodies, and drops idle pooled connections. Safe to call repeatedly; later requests return EBADF.
move fn close() Result[Void, Error]HttpClient.request#
Sends the request, with body as text or Bytes, and returns the response with its
body as a stream. max_response_bytes bounds the body (null sets no limit) and
timeout bounds the whole exchange (null waits without limit).
fn request(method HttpMethod, url String, headers HttpHeaders = headers(), body Writable = "", max_response_bytes Int? = null, timeout Duration? = null) Result[StreamingResponse, Error]HttpClient.request_raw#
Sends body as Bytes and returns the native response, for callers that buffer the
whole response body with RawResponse.read_all.
fn request_raw(method HttpMethod, url String, headers HttpHeaders, body Bytes, max_response_bytes Int? = null, timeout Duration? = null) Result[RawResponse, Error]HttpClient.request_stream#
Reads body to its end, then sends it as the request body. The upload is buffered,
not streamed, so the whole body must fit in memory.
fn request_stream(method HttpMethod, url String, headers HttpHeaders, move body ReadStream[Bytes], max_response_bytes Int? = null, timeout Duration? = null) Result[StreamingResponse, Error]HttpClientOptions Type#
Connection, redirect, cookie, decompression, and TLS settings for an HTTP client.
type HttpClientOptions {
max_redirects Int? = null
max_idle_connections Int? = null
max_header_bytes Int? = null
idle_timeout Duration? = null
decompress Bool = false
cookies Bool = false
tls TlsOptions = TlsOptions(
server_name: "",
roots_pem: "",
certificate_pem: "",
private_key_pem: "",
alpn: [],
require_client_certificate: false,
)
}HttpClientOptions.cookies#
When True, the client keeps an in-memory cookie jar for its lifetime, respecting public-suffix boundaries; when False (the default), no cookies are stored or sent automatically.
cookies Bool = falseHttpClientOptions.decompress#
When True, gzip-encoded responses are decoded transparently, with
max_response_bytes bounding the decoded size; when False (the default), bodies
arrive exactly as sent.
decompress Bool = falseHttpClientOptions.idle_timeout#
How long an idle pooled connection is kept before it is closed. null never expires it, and a negative duration is rejected.
idle_timeout Duration? = nullHttpClientOptions.max_header_bytes#
Largest accepted size of a response header block, in bytes. Must be positive; null uses the default of 1 MiB.
max_header_bytes Int? = nullHttpClientOptions.max_idle_connections#
Number of idle connections kept for reuse. Must be nonnegative; null sets no explicit cap.
max_idle_connections Int? = nullHttpClientOptions.max_redirects#
Most redirects followed per request. 0 returns the redirect response itself, null sets no cap, and a negative count is rejected. Redirects that downgrade from HTTPS, leave the network’s restrictions, or carry user info are refused.
max_redirects Int? = nullHttpClientOptions.tls#
TLS trust and client-certificate settings for https requests. The host name is
taken from each URL, so server_name is ignored.
tls TlsOptions = TlsOptions(
server_name: "",
roots_pem: "",
certificate_pem: "",
private_key_pem: "",
alpn: [],
require_client_certificate: false,
)HttpExchange Interface#
One streaming server exchange. Read or write incrementally and close when done. Received headers are an owned copy; repeated values stay separate.
interface HttpExchange {
var fn close() Void
fn headers() HttpHeaders
fn method() HttpMethod
fn path() String
fn protocol() String
fn query() String
var fn read(max_bytes Int? = null) Result[Bytes?, Error]
var fn send(status Int, headers HttpHeaders, body Bytes) Result[Void, Error]
var fn send_headers(status Int, headers HttpHeaders) Result[Void, Error]
var fn upgrade(allowed_origins List[String] = [], subprotocols List[String] = [], max_message_bytes Int? = null) Result[WebSocket, Error]
var fn write(data String) Result[Void, Error]
var fn write_bytes(data Bytes) Result[Void, Error]
}HttpExchange.close#
Ends the exchange, interrupting reads or writes in progress. Later operations return EBADF.
var fn close() VoidHttpExchange.headers#
Returns an owned copy of the request headers with every repeated value retained.
fn headers() HttpHeadersHttpExchange.method#
Returns the request method, using the Custom case for extension tokens.
fn method() HttpMethodHttpExchange.path#
Returns the percent-decoded request path with dot segments resolved. Requests with an encoded slash or NUL are rejected before the handler runs.
fn path() StringHttpExchange.protocol#
Returns the protocol the request arrived over, such as HTTP/1.1 or HTTP/2.0.
fn protocol() StringHttpExchange.query#
Returns the raw query string without the leading ?; it is empty when there is
null.
fn query() StringHttpExchange.read#
Returns the next chunk of the request body, at most max_bytes and never more
than 65536, or null at the end of the body. Reading past max_body_bytes returns
an Error of kind EOVERFLOW, and a non-positive max_bytes returns EINVAL.
var fn read(max_bytes Int? = null) Result[Bytes?, Error]HttpExchange.send#
Sends a whole response: the status line, headers, and body with its length
known, so the response carries Content-Length rather than chunked framing.
Requests with HEAD and statuses without a body get the head alone. The rules of
send_headers apply, body is bounded by max_response_bytes, and nothing else
may be sent afterwards.
var fn send(status Int, headers HttpHeaders, body Bytes) Result[Void, Error]HttpExchange.send_headers#
Sends the status line and headers once, before any body is written. The status
must be 200 through 599, header names cannot be Content-Length,
Transfer-Encoding, or Connection, and header bytes are bounded by
max_header_bytes. A second call returns EINVAL and a closed exchange returns
EBADF.
var fn send_headers(status Int, headers HttpHeaders) Result[Void, Error]HttpExchange.upgrade#
Switches the connection to a WebSocket after checking the Origin header.
Requests without an Origin are accepted. Otherwise the Origin must exactly match
an entry of allowed_origins or, when that list is empty, the request’s own
scheme and host.
subprotocols lists the protocols the server accepts, and max_message_bytes
must be positive when given. An exchange that already sent headers or upgraded
returns EINVAL, and a request that is not a valid WebSocket upgrade returns EIO.
var fn upgrade(allowed_origins List[String] = [], subprotocols List[String] = [], max_message_bytes Int? = null) Result[WebSocket, Error]HttpExchange.write#
Writes one chunk of the response body and flushes it.
send_headers must come first, and writing beyond max_response_bytes returns an
Error of kind EOVERFLOW. A write on a HEAD request succeeds and drops the
bytes, so a handler written for GET needs no HEAD case. Statuses 204 and 304
cannot have a body, so a write returns EINVAL.
var fn write(data String) Result[Void, Error]HttpExchange.write_bytes#
Writes one chunk of raw bytes with the same rules as write.
var fn write_bytes(data Bytes) Result[Void, Error]HttpHeaders Native type#
Mutable HTTP header fields. Names are ASCII case-insensitive, and each name holds separate values: Strings by default,
Bytes on request. Names keep their first-insertion order and spelling; values keep append order.
Headers have one owner: assignment moves them, mutation needs var, and clone() copies them.
type HttpHeaders {
}HttpHeaders.append#
Appends a String value under a valid HTTP name; an invalid name returns EINVAL. Requests and responses validate field values and framing again when they are sent.
var fn append(name String, value String) Result[Void, Error]HttpHeaders.append_bytes#
Appends raw bytes, for the rare field whose value is not UTF-8 text.
var fn append_bytes(name String, value Bytes) Result[Void, Error]HttpHeaders.clone#
Copies every name and value into independent headers.
fn clone() HttpHeadersHttpHeaders.contains#
Reports whether the name has any value, whatever its encoding.
fn contains(name String) BoolHttpHeaders.get#
Returns the first value as text, or null for an absent name. A value that is not valid UTF-8 is skipped; read it with get_all_bytes.
fn get(name String) String?HttpHeaders.get_all#
Returns every value as an owned list, empty for an absent name. A received value that is not valid UTF-8 is left out; read it with get_all_bytes.
fn get_all(name String) List[String]HttpHeaders.get_all_bytes#
Returns the raw bytes of every value as an owned list, or null for an absent name.
fn get_all_bytes(name String) List[Bytes]?HttpHeaders.names#
Returns the names in insertion order, each as spelled when first inserted.
fn names() List[String]HttpHeaders.remove#
Removes a name and its values; an absent name changes nothing. Previously returned value lists remain unchanged.
var fn remove(name String) VoidHttpMethod Enum#
Known HTTP methods, plus extension tokens validated by outgoing operations.
enum HttpMethod {
Get
Head
Post
Put
Patch
Delete
Connect
Options
Trace
Custom(value String)
}HttpMethod.Connect#
Establishes a tunnel to the request target.
ConnectHttpMethod.Custom#
Carries an extension token; requests reject empty or malformed tokens.
Custom(value String)HttpMethod.Delete#
Removes the selected representation.
DeleteHttpMethod.Get#
Requests the selected representation.
GetHttpMethod.Head#
Requests response metadata without a body.
HeadHttpMethod.Options#
Asks which communication options the target supports, without transferring a body.
OptionsHttpMethod.Patch#
Applies a partial modification.
PatchHttpMethod.Post#
Submits a representation for processing.
PostHttpMethod.Put#
Replaces the selected representation.
PutHttpMethod.Trace#
Requests a diagnostic loopback.
TraceHttpMethod.Custom.value#
The method token; it must be a non-empty HTTP token such as PURGE.
value StringHttpMethod.to_string#
Returns the method token; outgoing requests reject malformed Custom tokens.
fn to_string() StringHttpRequest Type#
Buffered request accepted by the simple HTTP server handler.
type HttpRequest {
method HttpMethod
path String
query String
headers HttpHeaders
body Bytes
protocol String = ""
}HttpRequest.body#
The complete request body, at most max_body_bytes long.
body BytesHttpRequest.headers#
The request headers as mutable fields with every repeated value retained.
headers HttpHeadersHttpRequest.method#
The request method, using the Custom case for extension tokens.
method HttpMethodHttpRequest.path#
The percent-decoded request path with dot segments resolved, so /a/../b arrives
as /b.
path StringHttpRequest.protocol#
The protocol the request arrived over, such as HTTP/1.1 or HTTP/2.0; empty
when not reported.
protocol String = ""HttpRequest.query#
The raw query string without the leading ?; empty when there is null.
query StringHttpResponse Type#
Buffered response returned by the simple HTTP server handler.
type HttpResponse {
status Int
body Bytes
headers HttpHeaders = headers()
}HttpResponse.body#
The response body bytes, which must not exceed max_response_bytes; the server
sets the content length.
body BytesHttpResponse.headers#
The response headers to send, empty by default; Content-Length,
Transfer-Encoding, and Connection are rejected with a 500 error.
headers HttpHeaders = headers()HttpResponse.status#
The HTTP status code, which must be 200 through 599; other values are answered with a 500 error.
status IntHttpResponseMetadata Type#
Response status and headers shared by buffered and streaming response access.
type HttpResponseMetadata {
status Int
headers HttpHeaders
protocol String = ""
}HttpResponseMetadata.headers#
The header fields, with every repeated value retained.
headers HttpHeadersHttpResponseMetadata.protocol#
The protocol the response used, such as HTTP/1.1 or HTTP/2.0; empty when the
source does not report one.
protocol String = ""HttpResponseMetadata.status#
The received status; editing metadata leaves wire/body behavior unchanged.
status IntHttpServer Type#
A running HTTP server. Close it, or drop it, to stop accepting and drain.
type HttpServer {
accepting Promise[Void]
bound String
stopped Bool
}HttpServer.accepting#
The accept loop, which owns the connection promises. It is declared first so it ends before what it uses.
accepting Promise[Void]HttpServer.bound#
The bound local address as host:port.
bound StringHttpServer.stopped#
Whether close has been called, so wait reports a normal stop.
stopped BoolHttpServer.address#
Returns the bound local address as host:port text, which reveals the port
chosen when listening on port 0.
fn address() StringHttpServer.close#
Stops accepting and asks every connection to finish: idle ones close at once,
requests in flight finish within grace, then the rest are cancelled. It returns
once the server has stopped, and consumes the server.
move fn close() Result[Void, Error]HttpServer.wait#
Waits until the server has stopped. Returns Ok after close, or the error that
ended accepting (EIO with the host’s text). timeout bounds the wait, and the
server is cancelled when it passes.
fn wait(timeout Duration? = null) Result[Void, Error]HttpServerOptions Type#
Request and response limits, deadlines, graceful shutdown, and TLS server settings.
type HttpServerOptions {
max_requests Int? = null
max_body_bytes Int? = null
max_response_bytes Int? = null
max_header_bytes Int? = null
timeout Duration? = null
grace Duration? = null
tls TlsOptions? = null
}HttpServerOptions.grace#
How long close waits for in-flight requests to finish before cancelling them.
null waits without limit and 0 cancels immediately.
grace Duration? = nullHttpServerOptions.max_body_bytes#
Largest accepted request body, in bytes. Must be nonnegative; null sets no cap.
max_body_bytes Int? = nullHttpServerOptions.max_header_bytes#
Largest accepted request header block and largest response header block, in bytes. Must be positive; null uses the default of 1 MiB.
max_header_bytes Int? = nullHttpServerOptions.max_requests#
Most requests handled at once; further requests are answered with 503. Must be positive; null sets no cap.
max_requests Int? = nullHttpServerOptions.max_response_bytes#
Most response body bytes a handler may write, in bytes. Must be nonnegative; null sets no cap.
max_response_bytes Int? = nullHttpServerOptions.timeout#
Per-request time budget covering reading the request, running the handler, and writing the response; an idle plain-HTTP connection waiting for its next request is also closed after it. A handler still running at the deadline is cancelled (its waits end and resource cleanup runs) and the request is answered 504; a WebSocket it opened is not limited. Must be positive; null sets no deadline.
timeout Duration? = nullHttpServerOptions.tls#
Some(options) serves HTTPS and negotiates HTTP/2 or HTTP/1.1 through ALPN; null, the default, serves plain HTTP/1.1.
tls TlsOptions? = nullRawResponse Type#
The native response a client operation returns: its body is read through
StreamingResponse.body. Metadata remains available after close; each metadata()
call returns an independent copy.
opaque type RawResponse {
}RawResponse.close#
Cancels the rest of the response and releases its connection. Safe to call repeatedly; reads afterwards return EBADF. A fully read body lets the connection be reused.
move fn close() Result[Void, Error]RawResponse.metadata#
Returns an independent copy of the response head (status and headers), including after close.
fn metadata() HttpResponseMetadataRawResponse.read_all#
Reads the rest of the body into one value, bounded by the request’s
max_response_bytes. A plain HTTP/1.1 body of known length arrives straight into
the result without intermediate copies.
fn read_all() Result[Bytes, Error]StreamingResponse Type#
A client response: the head and the body as a stream. Closing or dropping the body cancels the rest of the response and releases its connection; a fully read body lets the connection be reused.
type StreamingResponse {
metadata HttpResponseMetadata
body ReadStream[Bytes]
}StreamingResponse.body#
The body, at most 64 KiB per item. Reading past the request’s
max_response_bytes returns an Error of kind EOVERFLOW.
body ReadStream[Bytes]StreamingResponse.metadata#
Status and headers, available whether or not the body is read.
metadata HttpResponseMetadataStreamingResponse.close#
Closes the body, which cancels what is unread and releases the connection.
move fn close() Result[Void, Error]buffered Function#
Adapts a handler that maps a whole request to a whole response into an exchange
handler for serve. The request body is read in full first.
fn buffered(move handler fn(HttpRequest) HttpResponse) fn(var HttpExchange) Result[Void, Error] { ... }headers Function#
Creates empty mutable headers. No header values are joined or comma-combined.
fn headers() HttpHeaders { ... }json Function#
Builds a response whose body is value encoded as JSON, with
Content-Type: application/json. A value stringify cannot encode returns EIO with
its diagnostic.
fn json[T Data](status Int, value T) Result[HttpResponse, Error] { ... }native_handler Function#
The closure the runtime calls for each request: it presents the native exchange as
an HttpExchange to the program’s handler and answers 1 when the handler failed, 0
otherwise. The runtime reads only that flag, so the handler’s result (and the Error
it may hold) is released here, by this function’s own scope.
fn native_handler(move handler fn(var HttpExchange) Result[Void, Error]) fn(move NativeExchange) Int { ... }read_body Function#
Reads the rest of the request body into one value. A body over max_body_bytes of
the server’s options returns EOVERFLOW; limit also bounds it when given.
fn read_body(var exchange HttpExchange, limit Int? = null) Result[Bytes, Error] { ... }redirect Function#
Builds a redirect to location with an empty body. The status should be 301, 302,
303, 307, or 308; the default 303 sends a followed POST on as a GET.
fn redirect(location String, status Int = 303) Result[HttpResponse, Error] { ... }reply Function#
Sends response whole: its status and headers, then its body.
fn reply(var exchange HttpExchange, response HttpResponse) Result[Void, Error] { ... }text Function#
Builds a response with a UTF-8 text body and no headers.
fn text(status Int, body String) HttpResponse { ... }