std.http
std.http: the HTTP/1.1 wire format, `Server` on a fixed number of worker threads, and a client (`get`, `post`, `request`; `https://` through libcurl). `parse` reads one request from a byte buffer and says how many bytes it used, so a server can parse pipelined requests by parsing again from the rest. `writeResponse` builds a response. A handler takes a context pointer and a `*Request` and returns a `Response`; there are no closures.
Parsing is strict: lines end in CRLF, a header value has no bare CR, LF or NUL, and a request that has both Content-Length and Transfer-Encoding is refused. The size limits give distinct error tags, so the server can answer 400, 413, 414, 431 or 505 (`errorStatus`).
ParseError
pub error ParseError { Incomplete, BadRequest, UnsupportedVersion, RequestLineTooLong, HeadersTooLarge, BodyTooLarge, OutOfMemory }
Why `parse` gave no request. `Incomplete` is not a fault: the buffer holds only the start of a request, so read more bytes and parse again. The size tags are `RequestLineTooLong` (414), `HeadersTooLarge` (431) and `BodyTooLarge` (413); `BadRequest` (400) and `UnsupportedVersion` (505) are malformed input.
Limits
pub struct Limits {
maxRequestLine: usize
maxHeaders: usize
maxBody: usize
}
Size limits for `parse`, in bytes.
maxRequestLine: usize-
The request line, without its CRLF.
maxHeaders: usize-
All header lines together, with their CRLFs and the blank line.
maxBody: usize-
The body, after any chunked decoding.
defaultLimits
pub fn defaultLimits() Limits
8 KiB for the request line, 16 KiB for the headers, 1 MiB for the body.
Header
pub struct Header {
name: []u8
value: []u8
}
A header: both slices point into the buffer given to `parse`, or into the data of the response being built.
Request
pub struct Request {
method: []u8
target: []u8
minor: u8
headers: List(Header)
body: []u8
chunks: Builder
pub fn deinit(self: *mut Self)
pub fn header(self: *Self, name: []u8) ?[]u8
pub fn keepAlive(self: *Self) bool
pub fn path(self: *Self) []u8
pub fn query(self: *Self, alloc: Allocator, name: []u8) AllocError!?[]u8
pub fn form(self: *Self, alloc: Allocator, name: []u8) AllocError!?[]u8
pub fn cookie(self: *Self, name: []u8) ?[]u8
}
A parsed request. `method`, `target` and the headers point into the buffer given to `parse`, which must outlive the request; a chunked body is a copy owned by the request. Call `deinit` when done.
minor: u8-
0 for HTTP/1.0, 1 for HTTP/1.1.
body: []u8-
The body: empty when the request had none.
pub fn deinit(self: *mut Self)-
Frees the headers and the decoded chunked body.
pub fn header(self: *Self, name: []u8) ?[]u8-
The value of the first header called `name`, compared without regard to ASCII case; null when there is none.
pub fn keepAlive(self: *Self) bool-
Should the connection stay open after the response? HTTP/1.1 unless `Connection: close`; HTTP/1.0 only with `Connection: keep-alive`.
pub fn path(self: *Self) []u8-
The target without its query string.
pub fn query(self: *Self, alloc: Allocator, name: []u8) AllocError!?[]u8-
The first value of `name` in the query string, percent-decoded (`+` is a space) in `alloc`; null when there is none. See `queryValue`.
pub fn form(self: *Self, alloc: Allocator, name: []u8) AllocError!?[]u8-
The first value of the field `name` of a `application/x-www-form-urlencoded` body, decoded in `alloc`; null when there is none or the request has another content type. See `formValue`.
pub fn cookie(self: *Self, name: []u8) ?[]u8-
The value of the cookie `name` of the `Cookie` header, as sent; null when there is none. See `cookieValue`.
Parsed
pub struct Parsed {
request: Request
consumed: usize
}
The result of `parse`: the request and the number of bytes it took from the buffer (parse the rest for a pipelined request).
pathOf
pub fn pathOf(target: []u8) []u8
The target without its query string.
queryOf
pub fn queryOf(target: []u8) []u8
The query string of a target: what follows the first `?`, as sent; empty when there is none.
percentDecode
pub fn percentDecode(alloc: Allocator, s: []u8) AllocError![]mut u8
Decodes `%XX` escapes of `s` in `alloc`. A `%` not followed by two hex digits stays as it is. `+` stays a `+`; `formDecode` makes it a space.
formDecode
pub fn formDecode(alloc: Allocator, s: []u8) AllocError![]mut u8
Like `percentDecode`, and each `+` becomes a space: the decoding of a query string or a form body.
queryValue
pub fn queryValue(alloc: Allocator, pairs: []u8, name: []u8) AllocError!?[]u8
The first value of `name` in `pairs`, a query string or a form body (`a=1&b=2`), with names and value decoded by `formDecode` in `alloc`; a pair without `=` has the value "". Null when no pair has the name.
formValue
pub fn formValue(alloc: Allocator, contentType: ?[]u8, body: []u8, name: []u8) AllocError!?[]u8
`queryValue` of `body` when `contentType` is `application/x-www-form-urlencoded` (parameters such as `; charset=utf-8` and ASCII case are ignored); null for any other type, or none.
cookieValue
pub fn cookieValue(header: []u8, name: []u8) ?[]u8
The value of the cookie `name` in the value of a `Cookie` header (`a=1; b=2`): spaces around a pair are trimmed and the value is not decoded. Null when there is none.
Response
pub struct Response {
status: u16
headers: []Header
body: []u8
streaming: bool = false
pub fn stream(self: *mut Self)
pub fn header(self: *Self, name: []u8) ?[]u8
}
A response: the one a server handler fills for `writeResponse` (do not put Content-Length or Transfer-Encoding in `headers`: the writer sets the length itself), and the one a client call returns.
streaming: bool = false-
Set by `stream()`; a client response never has it.
pub fn stream(self: *mut Self)-
Turns the response of a server handler into a server-sent event stream (O3.6b). The server writes the status line, the handler's `headers`, `Content-Type: text/event-stream`, `Cache-Control: no-cache` and `Connection: keep-alive`, with no `Content-Length` (`Content-Type` is not to be in `headers`). A non-empty `res.body` is written as is, right after the head, as the first chunk of the stream (O3.6d): the handler formats it as event frames (`event: build\ndata: x\n\n`), with no chunked framing. Then the server keeps the connection open: `Server.broadcast` sends events to it until the client leaves or the server stops, and none is sent before the first chunk is written. A `HEAD` request is answered as a plain response.
pub fn header(self: *Self, name: []u8) ?[]u8-
The value of the first header called `name`, compared without regard to ASCII case; null when there is none.
errorStatus
pub fn errorStatus(e: ParseError) u16
The HTTP status that answers a `ParseError`: 400, 413, 414, 431, 500 or 505. `Incomplete` is 400 too, for a peer that closed in mid-request.
parse
pub fn parse(alloc: Allocator, buf: []u8, limits: Limits) ParseError!Parsed
Parses one HTTP/1.1 request from the start of `buf`: the request line, the headers, then the body by Content-Length or `Transfer-Encoding: chunked`. Returns the request and the bytes used; `Incomplete` when `buf` holds only part of a request. A limit is checked as soon as it is passed, not when the request is complete.
reason
pub fn reason(status: u16) []u8
The standard reason phrase of `status` ("OK" for 200); "Unknown" for a code without one.
dateHeader
pub fn dateHeader(alloc: Allocator, at: i64) AllocError!Header
A `Date` header for `at`, as IMF-fixdate (`Date: Sat, 10 Oct 2026 07:20:00 GMT`), its value in new memory from `alloc` (free it with `alloc.free`). `dateHeader(alloc, time.now())` stamps a response; the server does not add one itself.
writeResponse
pub fn writeResponse(out: *mut Builder, res: Response) AllocError!void
Appends the response to `out`: the status line with its reason phrase, the headers of `res`, `Content-Length` and the body.
listen
pub fn listen(comptime T: type, host: []u8, port: u16, ctx: *mut T, handler: fn(*mut T, *Request, *mut Response, Allocator)) ListenError!Server
Listens on `host:port` (port 0 lets the system pick one) for a context of type `T`; `ctx` must stay valid until `run` has returned.
Server
pub struct Server {
listener: Listener
ctx: [*]u8
handler: fn([*]u8, *Request, *mut Response, Allocator)
limits: Limits
idleMs: u32
workers: u32
stopped: Atomic(u32)
accepting: Atomic(u32)
loopback: []u8
streamLock: Mutex
streamHead: ?*mut Open
openLock: Mutex
openGpa: General
crew: []mut Worker
pub fn port(self: *Self) u16
pub fn run(self: *mut Self, alloc: Allocator) AllocError!void
pub fn streams(self: *mut Self) usize
pub fn broadcast(self: *mut Self, alloc: Allocator, event: []u8, data: []u8) AllocError!usize
pub fn stop(self: *mut Self)
}
Serves HTTP/1.1 on a TCP port with a fixed number of threads (`workers`), each accepting connections and serving the ones it holds, with keep-alive and pipelining. Every handler gets the context pointer given to `listen` (the `std.thread.spawn(T, f, arg)` shape; there are no closures). A handler is `fn(ctx: *mut T, req: *Request, res: *mut Response, alloc: Allocator)`: it fills `res` (status 200 and no body to begin with); `alloc` is an arena that lives until the response is written (the connection's arena, reset once the response is all written), so a handler allocates and never frees, and keeps no pointer into it past the call. Handlers run on many threads at once: what they share through `ctx` needs a `std.sync.Mutex` or an `Atomic`. A `HEAD` request is answered like a `GET` (the handler sees the method and may fill the same body): the server writes the status line, the headers and the `Content-Length` of `res.body`, and not the body.
Make it with `listen` (which listens, so `port()` is known at once, also for port 0), run `run` on a thread, and end it with `stop`.
Slow clients (O3.9a): connections are non-blocking, and what the socket does not take of a response at once stays in the connection's arena until `poll` says there is room, so a client that reads slowly holds up only itself. Its next request (pipelined or not) is answered only after the response is all written, and a client that takes no bytes for `idleMs` is closed. A write error closes the connection.
Slow handlers (O3.9b): a worker that has run one handler for more than 20 ms has its other connections taken over by another worker, which serves them from then on, so a slow handler holds up only its own connection. With `workers = 1` there is no other worker to take them.
New connections (O3.9c): on Linux each worker has a listener of its own on the port (`SO_REUSEPORT`, `net.listenShared`), so the kernel hands a new connection to one worker and wakes only that one; the connections waiting on the listener of a worker whose handler is slow are taken with its other connections. On macOS, which does not spread connections over such listeners, the workers share one. Because of `SO_REUSEPORT`, a second server of the same user on the same port does not fail on Linux.
Server-sent events (O3.6b): a handler that calls `res.stream()` makes its connection a stream, which `broadcast` writes events to from any thread. Threading: the worker that accepted the connection owns it (it reads and closes it, and discards what the client sends); `streamLock` guards the list of open streams, and every write to a stream happens under it. A worker takes the lock to add a stream (once the response head and the body, the first chunk, are written, so no event comes before them) and to remove it before it closes the connection, so `broadcast` never writes to a closed or reused descriptor. A stream that cannot take an event at once (the client is gone, or its socket buffer is full) is dropped, never waited for: the writing thread removes it from the list and the owning worker closes it within about 100 ms. A stream has no idle timeout, and `stop` closes it.
limits: Limits-
The size limits for parsing requests; `defaultLimits()` to begin with.
idleMs: u32-
How long an open connection may wait for its next request, in milliseconds (5000 to begin with); `stop` takes at most this long to finish the connections that are open.
workers: u32-
How many threads `run` serves on (at most 64): the number of CPUs, at least 2, to begin with. Set it before `run`. A handler that blocks holds up only its own connection (see `Server`).
pub fn port(self: *Self) u16-
The port it listens on.
pub fn run(self: *mut Self, alloc: Allocator) AllocError!void-
Serves until `stop` (or SIGINT or SIGTERM after `std.os.onStop()`): starts `workers - 1` threads and serves on this one too. Each worker waits (`poll`) on its listener (see `Server`) and on the connections it has accepted, and answers the requests that arrive; the kernel spreads the connections over the workers. Then it finishes the answered responses (see `stop`), closes the open connections, waits for the workers and closes the listener. `alloc` is used only by this thread, for the bookkeeping.
pub fn streams(self: *mut Self) usize-
The number of open event streams.
pub fn broadcast(self: *mut Self, alloc: Allocator, event: []u8, data: []u8) AllocError!usize-
Writes one event frame to every open stream, from any thread: `event: <event>` (left out when `event` is empty), one `data:` line per line of `data`, and a blank line. Gives the number of streams it wrote to; a stream that cannot take the frame is dropped (see `Server`). `alloc` holds the frame for the call. Do not call it after `run` has returned.
pub fn stop(self: *mut Self)-
Asks `run` to return: sets the flag and connects once to wake up the workers. Safe to call from any thread; the listener stops accepting, a request that is being handled is answered (the rest of a response the socket has not taken is written first, for at most `idleMs`), the other open connections are closed, and `run` returns within about 100 ms. SIGINT or SIGTERM does the same after `std.os.onStop()`.
lastError
pub fn lastError(alloc: Allocator) AllocError![]mut u8
What libcurl said about the most recent `https://` connect of this program that failed (any thread): "https connect to <host:port> failed (libcurl <code>): <text>", a copy in `alloc`; "" when none failed. The error tag (`TlsFailed`, `ConnectFailed`, ...) is what to act on; this text is for a log line or a bug report.
ClientError
pub error ClientError { InvalidUrl, UnsupportedScheme, HttpsUnsupported, TlsFailed, InvalidRequest, UnknownHost, ConnectionRefused, ConnectFailed, TimedOut, ConnectionClosed, BadResponse, HeadersTooLarge, BodyTooLarge, TooManyRedirects, OutOfMemory }
Why a client call gave no response. `InvalidUrl`, `UnsupportedScheme` (not http or https) come from the URL; `HttpsUnsupported` is an `https://` URL in a program built without libcurl; `InvalidRequest` is a method or header that cannot be sent; the connect tags are `UnknownHost`, `ConnectionRefused`, `ConnectFailed` and `TimedOut`; `TlsFailed` is a TLS handshake or certificate failure (an untrusted or expired certificate, a wrong host name, a bad `caFile`). `ConnectionClosed` is a connection that failed or ended before the response was complete; `BadResponse` is malformed input. `HeadersTooLarge`, `BodyTooLarge` and `TooManyRedirects` are limits.
ClientOptions
pub struct ClientOptions {
timeoutMs: u32 = 10000
maxBodyBytes: usize = 16777216
followRedirects: bool = false
caFile: ?[]u8 = null
}
Options of `requestWith`.
timeoutMs: u32 = 10000-
How long one wait for data may take, in milliseconds (10000 to begin with). It is not a limit on the whole call.
maxBodyBytes: usize = 16777216-
The longest response body, after any chunked decoding (16 MiB to begin with).
followRedirects: bool = false-
Follow 301, 302, 303, 307 and 308 with a `Location` (at most 10 times). Off to begin with: the redirect is returned as it is.
caFile: ?[]u8 = null-
A file of PEM certificates that `https://` trusts instead of the system's store (null to begin with: the system's store). The certificate and the host name are always checked.
Url
pub struct Url {
https: bool
host: []u8
port: u16
authority: []u8
target: []u8
}
A URL split by `parseUrl`; the slices point into the string given.
host: []u8-
The host name or address, without the brackets of an IPv6 address.
port: u16-
The port written, else 80 (443 for https).
authority: []u8-
`host[:port]` as written, for the `Host` header.
target: []u8-
The path and query as written, without any fragment. It is empty or starts with `?` when the URL has no path; the request line then gives `/`.
parseUrl
pub fn parseUrl(url: []u8) ClientError!Url
Splits `http://host[:port][/path][?query]`; `[::1]` is an IPv6 host and a `#fragment` is dropped. `https://` parses (default port 443) and is refused later, by the request. Other schemes are `UnsupportedScheme`; a missing scheme, an empty host, user info, a bad port or a space or control character is `InvalidUrl`.
request
pub fn request(alloc: Allocator, method: []u8, url: []u8, headers: []Header, body: []u8) ClientError!Response
`requestWith` with the default `ClientOptions`: sends `method` to `url` with the extra `headers` and the `body`, and returns the response. The response (its headers and body) is allocated from `alloc`, which should be an `Arena` that the caller frees as a whole. The request is HTTP/1.1 with `Host`, `Content-Length` (for a body, and for POST, PUT and PATCH) and `Connection: close`; `headers` must not name Content-Length, Transfer-Encoding or Connection, and a `Host` among them replaces the automatic one. A status of 3xx or 4xx is a response, not an error.
get
pub fn get(alloc: Allocator, url: []u8) ClientError!Response
`request` with a GET and no body.
post
pub fn post(alloc: Allocator, url: []u8, contentType: []u8, body: []u8) ClientError!Response
`request` with a POST of `body`, sent with the `Content-Type` `contentType`.
requestWith
pub fn requestWith(alloc: Allocator, opts: ClientOptions, method: []u8, url: []u8, headers: []Header, body: []u8) ClientError!Response
`request` with `opts`. With `followRedirects`, a 301, 302 or 303 turns a request other than GET or HEAD into a GET without a body, a 307 or 308 repeats it, and the extra `headers` go only to the same host and port. Every response on the way stays allocated in `alloc`.