abla/http

Generated from source.

Import with import "abla/http".

Source: abla/http/entry.ab

HttpHeader (class)

class HttpHeader(val name: string, val value: string)

One header field with its original name spelling and value.

HttpRequest (class)

class HttpRequest(
    val method: string,
    val path: string,
    val query: string,
    val headers: array<HttpHeader>,
    val body: string,
    val parameterNames: array<string>,
    val parameterValues: array<string>,
    // Accepted socket peer; never taken from forwarding headers.
    val peerAddress: SocketPeerAddress? = null
)

An HTTP request with its method, path, raw query, headers, and body. Route parameters use parallel name and value arrays. The optional peer address identifies the accepted socket peer.

httpRequestWithAddress (fun)

fun httpRequestWithAddress(request: HttpRequest,
    peer: SocketPeerAddress?): HttpRequest

Attach transport metadata to an already parsed request.

httpRequestWithPeer (fun)

fun httpRequestWithPeer(request: HttpRequest, descriptor: int): HttpRequest

Returns the request with the socket peer attached, or with no peer if the address lookup fails.

HttpResponse (class)

class HttpResponse(
    val status: int,
    val headers: array<HttpHeader>,
    val body: string
)

An HTTP response with the numeric status, ordered headers, and response body bytes.

HttpTransportResult (class)

class HttpTransportResult(
    val bytes: string,
    val succeeded: bool,
    // A custom transport returns a complete exchange unless it says otherwise.
    val eof: bool = true
)

HTTP remains independent of TLS policy. A transport receives already-framed request bytes and returns bounded response bytes; TLS modules can implement the same callback without changing request, response, or client code.

HttpClientResult (class)

class HttpClientResult(
    val response: HttpResponse,
    val succeeded: bool,
    val complete: bool,
    // Why the request was not sent (httpClientRequestError names the part), "" otherwise.
    val error: string = ""
)

A response and flags reporting whether parsing succeeded and whether framing identified a complete response.

HttpCoreChunkDecode (class)

class HttpCoreChunkDecode(
    val body: string,
    val consumed: int,
    val complete: bool,
    val valid: bool,
    // For incomplete input: the offset of the first chunk element (a size line with its data, or the last chunk and its trailers) that is not complete;
    // `body` holds everything before it, so a caller may drop those bytes and decode the rest when more arrives.
    val resume: int = 0,
    // For input that ends inside a chunk's data: the input size at which that chunk is complete (zero otherwise).
    val need: int = 0
)

Holds decoded body bytes and consumed input length, with separate flags for a complete and a valid chunk stream.

HttpClient (class)

class HttpClient(
    val authority: string,
    val exchange: (string, int, int) -> HttpTransportResult,
    val maximumResponseBytes: int,
    val timeoutMilliseconds: int
)

A client with a Host authority, transport callback, response byte limit, and timeout. Use send to render requests and parse responses.

HttpPathMatch (class)

class HttpPathMatch(
    val matched: bool,
    val names: array<string>,
    val values: array<string>
)

Reports a path match and the captured parameter names and values in matching order.

HttpRoute (class)

class HttpRoute(
    val method: string,
    val pattern: string,
    val version: string,
    val handler: (HttpRequest) -> HttpResponse
)

Associates an HTTP method, path pattern, and optional API version with a handler.

HttpRouter (class)

class HttpRouter(
    val versionHeader: string,
    val routes: array<HttpRoute>,
    val literalRouteBuckets: array<array<int>> = [],
    val parameterizedRouteIndexes: array<int> = [],
    val routeFingerprints: array<int> = [],
    val indexedRouteMarkers: array<int> = []
)

Holds registered routes, their dispatch indexes, and the header used to select an API version.

HttpVersionedRouter (class)

class HttpVersionedRouter(
    val router: HttpRouter,
    val version: string
)

Registers handlers on an existing router under one API version.

httpRouter (fun)

fun httpRouter(versionHeader: string = "Abla-Version"): HttpRouter

Creates an empty router that reads the requested API version from versionHeader.

httpAsciiEqualInsensitive (fun)

fun httpAsciiEqualInsensitive(left: string, right: string): bool

Returns whether left and right match after folding ASCII letter case.

HttpRequest.header (extension fun)

fun HttpRequest.header(name: string): string

Returns the last matching header's value, comparing name without regard to ASCII case. Returns an empty string when absent.

HttpRequest.parameter (extension fun)

fun HttpRequest.parameter(name: string): string

Returns the last route parameter named name, falling back to a raw query lookup if there is no route match. Returns an empty string when absent.

HttpRequest.routeParameter (extension fun)

fun HttpRequest.routeParameter(name: string): string

Route-only lookup for applications that do not want query fallback.

HttpRequest.queryParameter (extension fun)

fun HttpRequest.queryParameter(name: string): string

Query-only lookup for applications that do not need the combined route-precedence convenience of parameter().

HttpRequest.queryParameterDecoded (extension fun)

fun HttpRequest.queryParameterDecoded(name: string): string?

The value of a query parameter with its form encoding undone (percentDecode in query mode: %XX escapes and + as a space), or null when the parameter is absent or empty, or its value is malformed (a bad escape or invalid UTF-8). queryParameter returns the raw text; the name is matched as written in both.

httpRequest (fun)

fun httpRequest(
    method: string,
    path: string,
    body: string = "",
    headers: array<HttpHeader> = []
): HttpRequest

Constructs a request from method, path, body, and headers. The query and route parameters start empty. The path is stored as supplied.

httpGet (fun)

fun httpGet(path: string, headers: array<HttpHeader> = []): HttpRequest

Constructs a GET request for path with headers and an empty body.

httpPost (fun)

fun httpPost(
    path: string,
    body: string,
    headers: array<HttpHeader> = []
): HttpRequest

Constructs a POST request for path with the supplied body and headers.

httpText (fun)

fun httpText(body: string, status: int = 200): HttpResponse

Returns a response with status, the supplied body, and Content-Type text/plain with UTF-8 charset.

httpJson (fun)

fun httpJson(body: string, status: int = 200): HttpResponse

Low-level helper for a body which is already valid encoded JSON. Import abla/http/json and use httpJsonValue when starting from a Json tree.

httpStatusReason (fun)

fun httpStatusReason(status: int): string

Returns the reason phrase for a recognized HTTP status, or Unknown Status when the code has no entry.

HttpResponse.renderHeaders (extension fun)

fun HttpResponse.renderHeaders(): string

Serializes the HTTP/1.1 status line and headers, ending each with CRLF. Adds missing Content-Length and Connection headers except for status 101. The blank line and body are left to the caller.

HttpResponse.render (extension fun)

fun HttpResponse.render(): string

Returns the HTTP/1.1 response bytes, including the blank line and body.

HttpResponse.renderHead (extension fun)

fun HttpResponse.renderHead(): string

Returns the HTTP/1.1 status and headers followed by a blank line. Content-Length still describes the underlying body.

HttpRequest.renderForClient (extension fun)

fun HttpRequest.renderForClient(authority: string): string

Serializes an HTTP/1.1 request and body. Uses authority for Host when absent and fills missing Content-Length and Connection headers. Returns "" for a request whose parts cannot be sent as they are (httpClientRequestError): nothing of it is written.

httpLineEnd (fun)

fun httpLineEnd(input: string, begin: int): int

Returns the offset of the first CRLF at or after begin, or the input length if none is found.

httpHeaderEnd (fun)

fun httpHeaderEnd(input: string): int

Returns the byte offset immediately after the first CRLF CRLF delimiter in input, or -1 if the delimiter is absent.

httpResponseStatusAt (fun)

fun httpResponseStatusAt(input: string, begin: int): int

The status at a response start, or 0 until its status line is complete.

httpFinalResponseOffset (fun)

fun httpFinalResponseOffset(input: string): int

Informational responses precede the final response; 101 is the terminal upgrade response. Keep an incomplete interim header for the next read.

httpRequestFraming (fun)

fun httpRequestFraming(request: HttpRequest, http10: bool, maximumBody: int): int

How a request's body is framed: -1 when its framing is malformed and the request is to be refused (400, then close, nothing of the buffer read again), -2 when it is chunked, else the Content-Length (0 when there is none). Strict on purpose: a request read with a different length than its sender (or a proxy in front) meant makes the bytes after it a different request. Refused: an empty or non-digit Content-Length or one over maximumBody; two Content-Lengths that differ; Content-Length together with Transfer-Encoding; a Transfer-Encoding other than exactly "chunked" (identity, gzip, "chunked, gzip", unknown) or given twice, and any in an HTTP/1.0 request; the look-alike names Content_Length and Transfer_Encoding (some backends map the underscore to a hyphen); and, whatever the header is named, whitespace before its colon or a folded line (RFC 9112 5.1, 6.1, 6.3). A refused request is a 400 on purpose, not a 501 for a coding this server does not know: it closes the connection either way.

httpClientRequestError (fun)

fun httpClientRequestError(method: string, target: string, host: string, headers: array<HttpHeader>): string

Why the clients refuse to send a request with these parts, or "" when they may: a method that is not a token, a target with a space or a control byte, a host that is not a host, a header name that is not a token, or a header value with a control byte other than tab. Each of these would be written to the wire as it is (a CR LF in a path or a header value from a program's input would start another header or another request: request splitting); they are what this library's servers refuse.

httpDecimalLength (fun)

fun httpDecimalLength(value: string, maximum: int): int

Reads decimal digits in value under the supplied maximum. Returns -1 for empty or nondecimal input or when the accumulated length exceeds the bound.

httpCoreHeaderTokenContains (fun)

fun httpCoreHeaderTokenContains(value: string, wanted: string): bool

Returns true if a comma-separated header token matches wanted after trimming spaces and tabs and folding ASCII case.

httpChunkExtensionsValid (fun)

fun httpChunkExtensionsValid(input: string, begin: int, end: int): bool

Whether input[begin, end) is what may follow a chunk size on its line: nothing, or extensions ;name, ;name=token and ;name="quoted string" (RFC 9112 7.1.1, tabs and spaces allowed after a semicolon). A bare CR, any other control byte, an empty name or a value that is neither a token nor a quoted string makes the chunked body malformed: a peer that ends the line at a bare CR or LF reads the bytes after it as something else.

httpTrailerLineValid (fun)

fun httpTrailerLineValid(input: string, begin: int, end: int): bool

Whether input[begin, end) (one line of a chunked body's trailer section, without its CRLF) is a field line a recipient may read: a token name, a colon and a value of visible characters, spaces, tabs and bytes over 127. A folded line (one that starts with a space or tab), a line without a colon, a control byte, and the fields that frame a message (Content-Length, Transfer-Encoding) are not (RFC 9110 6.5.1: they must not be sent in a trailer, and are never applied).

httpCoreDecodeChunked (fun)

fun httpCoreDecodeChunked(
    input: string,
    maximumBody: int = 1048576
): HttpCoreChunkDecode

Decodes a chunked HTTP body from input, limiting decoded data to maximumBody bytes. The result includes the body, bytes consumed, and separate flags for valid framing and a complete body.

httpReadRequest (fun)

fun httpReadRequest(
    connection: TcpConnection,
    maximumHeader: int = 65536,
    maximumBody: int = 1048576
): string

Reads request bytes within the supplied bounds and the default deadlines of httpServeOptions(), returning empty text for rejected framing or a deadline, or partial bytes when the stream ends early.

httpParseRequest (fun)

fun httpParseRequest(input: string): HttpRequest

Parses the request line, headers, and available body bytes from input, without attaching a peer address. This parser can return partial requests. Use the framing checks when receiving a request from a connection.

httpParseRequestFrom (fun)

fun httpParseRequestFrom(input: string, peer: SocketPeerAddress?): HttpRequest

httpParseRequest with the accepted socket peer set on the request being built, so no copy of it is made to attach the peer.

httpTokenByte (fun)

fun httpTokenByte(byte: int): bool

Whether byte may be in a header name: a token character (RFC 9110 5.6.2).

httpMalformedLineHeader (fun)

fun httpMalformedLineHeader(): HttpHeader

What a request head line that no reader can take as a header leaves in request.headers: a line without a colon or with an empty name (a folded line is one), or one with a bare LF or CR in it, a control byte but a tab (or DEL) in its value, or a byte in its name that is not a token character (RFC 9112 2.2, 5.1, 5.2). The line is dropped from the parse as before, but this marker (a name that begins with a space, which httpRequestFraming refuses, and an empty value) says it was there, so a request with such a line is refused, not read two ways.

httpHasControlByte (fun)

fun httpHasControlByte(input: string, begin: int, end: int): bool

Whether input[begin, end) has a byte under 32.

httpValueHasControl (fun)

fun httpValueHasControl(input: string, begin: int, end: int): bool

Whether the header value in input[begin, end) has a control byte other than a tab, or DEL (RFC 9110 5.5).

httpNameHasNonToken (fun)

fun httpNameHasNonToken(input: string, begin: int, end: int): bool

Whether the header name in input[begin, end) has a byte that is not a token character.

HttpResponse.header (extension fun)

fun HttpResponse.header(name: string): string

Returns the last response header matching name without regard to ASCII case, or an empty string when absent.

httpParseResponseBounded (fun)

fun httpParseResponseBounded(
    input: string,
    maximumBodyBytes: int,
    responseToHead: bool = false,
    eof: bool = true
): HttpClientResult

Parses the final response from input after any interim responses. responseToHead suppresses the body and eof permits close-delimited completion. maximumBodyBytes constrains completion. Check both succeeded and complete before using the response.

httpResponseLengthsDiffer (fun)

fun httpResponseLengthsDiffer(headers: array<HttpHeader>): bool

A response with two Content-Lengths that differ has two answers to where its body ends: it is an error, not a guess (RFC 9112 6.3), so a reader stops at once and reports it instead of waiting for more. That holds for a HEAD, 204 or 304 response too (ambiguous metadata). With a Transfer-Encoding the Content-Length is not used at all, so that case needs no check.

httpParseResponse (fun)

fun httpParseResponse(input: string): HttpClientResult

Parses input as a response with a 1 MiB body limit, treating the input as ended. Returns the parsed status, headers and body with success and completeness flags.

httpRequestIsHead (fun)

fun httpRequestIsHead(request: string): bool

The transport receives a rendered request; HEAD responses end at headers.

httpClient (fun)

fun httpClient(
    authority: string,
    exchange: (string, int, int) -> HttpTransportResult,
    maximumResponseBytes: int = 1048576,
    timeoutMilliseconds: int = 5000
): HttpClient

Creates a client using authority for Host and calling exchange with serialized request bytes, maximumResponseBytes, and timeoutMilliseconds. Transport and parse errors are reported by send.

httpExchangeDeadline (fun)

fun httpExchangeDeadline(deadlineMilliseconds: int): int

When an exchange of at most deadlineMilliseconds must end (0: never).

httpExchangeWait (fun)

fun httpExchangeWait(deadline: int, timeoutMilliseconds: int): int

How long the next read or write of an exchange may wait: timeoutMilliseconds, or what is left before deadline when that's shorter, and 0 when none is left.

httpIpv4Client (fun)

fun httpIpv4Client(
    authority: string,
    address: string,
    port: int,
    maximumResponseBytes: int = 1048576,
    timeoutMilliseconds: int = 5000,
    // A limit on the whole exchange (0: none). The timeout bounds each read and
    // write, so a peer sending a byte at a time can otherwise hold the caller.
    deadlineMilliseconds: int = 0
): HttpClient

Creates a client sending Host authority over IPv4 to address and port. Caps response bytes at maximumResponseBytes, bounds individual waits by timeoutMilliseconds, and optionally caps the whole exchange by deadlineMilliseconds. Errors are reported by send.

httpUnixClient (fun)

fun httpUnixClient(
    authority: string,
    address: UnixSocketAddress,
    maximumResponseBytes: int = 1048576,
    timeoutMilliseconds: int = 5000,
    deadlineMilliseconds: int = 0
): HttpClient

HTTP/1.1 over a local stream, for services such as Docker's API.

HttpClient.send (extension fun)

fun HttpClient.send(request: HttpRequest): HttpClientResult

Renders request, runs the client's transport, and parses the response. Transport failure returns an empty response with status zero and both result flags false.

httpMatchPath (fun)

fun httpMatchPath(pattern: string, path: string): HttpPathMatch

Matches literal and colon-prefixed path segments and returns any captured parameters with the match result.

HttpRouter.get (extension fun)

fun HttpRouter.get(
    pattern: string,
    handler: (HttpRequest) -> HttpResponse
): HttpRouter

Registers an unversioned GET handler for path pattern. Returns this router for chaining.

HttpRouter.addRoute (extension fun)

fun HttpRouter.addRoute(
    method: string,
    pattern: string,
    version: string,
    handler: (HttpRequest) -> HttpResponse
): HttpRouter

Registers the handler for a method, pattern, and optional version, then returns the same router.

HttpRouter.route (extension fun)

fun HttpRouter.route(
    method: string,
    pattern: string,
    handler: (HttpRequest) -> HttpResponse
): HttpRouter

Registers handler for an unversioned method and path pattern, then returns the same router for chaining.

HttpRouter.post (extension fun)

fun HttpRouter.post(
    pattern: string,
    handler: (HttpRequest) -> HttpResponse
): HttpRouter

Registers an unversioned POST handler for path pattern. Returns this router for chaining.

HttpRouter.head (extension fun)

fun HttpRouter.head(
    pattern: string,
    handler: (HttpRequest) -> HttpResponse
): HttpRouter

Registers an unversioned HEAD handler for path pattern. Returns this router for chaining.

HttpRouter.put (extension fun)

fun HttpRouter.put(
    pattern: string,
    handler: (HttpRequest) -> HttpResponse
): HttpRouter

Registers an unversioned PUT handler for path pattern. Returns this router for chaining.

HttpRouter.patch (extension fun)

fun HttpRouter.patch(
    pattern: string,
    handler: (HttpRequest) -> HttpResponse
): HttpRouter

Registers an unversioned PATCH handler for path pattern. Returns this router for chaining.

HttpRouter.delete (extension fun)

fun HttpRouter.delete(
    pattern: string,
    handler: (HttpRequest) -> HttpResponse
): HttpRouter

Registers an unversioned DELETE handler for path pattern. Returns this router for chaining.

HttpRouter.options (extension fun)

fun HttpRouter.options(
    pattern: string,
    handler: (HttpRequest) -> HttpResponse
): HttpRouter

Registers an unversioned OPTIONS handler for path pattern. Returns this router for chaining.

HttpRouter.version (extension fun)

fun HttpRouter.version(versionName: string): HttpVersionedRouter

Returns a view of this router that registers handlers under versionName.

HttpVersionedRouter.get (extension fun)

fun HttpVersionedRouter.get(
    pattern: string,
    handler: (HttpRequest) -> HttpResponse
): HttpRouter

Registers a GET handler for path pattern under this view's version. Returns the underlying router.

HttpVersionedRouter.post (extension fun)

fun HttpVersionedRouter.post(
    pattern: string,
    handler: (HttpRequest) -> HttpResponse
): HttpRouter

Registers a POST handler for path pattern under this view's version. Returns the underlying router.

HttpVersionedRouter.head (extension fun)

fun HttpVersionedRouter.head(
    pattern: string,
    handler: (HttpRequest) -> HttpResponse
): HttpRouter

Registers a HEAD handler for path pattern under this view's version. Returns the underlying router.

HttpRouter.dispatch (extension fun)

fun HttpRouter.dispatch(request: HttpRequest): HttpResponse

Routes request by method, path, and requested version. HEAD can fall back to GET. Passes matched route parameters to the handler and returns its response, or status 404 without a match.

HttpServeOptions (class)

class HttpServeOptions(
    val firstByteTimeoutMilliseconds: int = 10000,
    val requestHeadTimeoutMilliseconds: int = 30000,
    val requestTimeoutMilliseconds: int = 120000,
    val responseTimeoutMilliseconds: int = 30000,
    val maximumHeaderBytes: int = 65536,
    val maximumBodyBytes: int = 1048576
)

Sets the deadlines and bounds of the blocking server (serveHttp, serveHttpOnListener, serveHttpOnce), which reads one connection at a time. In milliseconds, 0 turning a deadline off: firstByteTimeoutMilliseconds closes a connection that sends nothing that long after it was accepted (a browser's speculative connection, a probe, an attacker: while a connection waits the server serves no other), requestHeadTimeoutMilliseconds one whose request head is not complete that long after its first byte, requestTimeoutMilliseconds one whose whole request (head and body) is not complete that long after its first byte, responseTimeoutMilliseconds one that does not take the whole response in that time. A connection that runs out of time is closed without an answer. The deadlines bound one connection, not the server: it still serves one connection at a time, so put it behind a proxy that limits connections per address, or use the event server (abla/http/event), which reads many connections at once.

httpServeOptions (fun)

fun httpServeOptions(): HttpServeOptions

The options serveHttp uses: ten seconds to a first byte, thirty to the end of the head, two minutes to the end of the request, thirty to take the response, a 64 KiB head and a 1 MiB body.

HttpReadOutcome (class)

class HttpReadOutcome(val request: string, val timedOut: bool)

A request read from a connection (empty when its framing was refused, or when the stream ended before its head), and whether a deadline ended the reading.

httpReadRequestWithin (fun)

fun httpReadRequestWithin(connection: TcpConnection, options: HttpServeOptions): HttpReadOutcome

Reads one request from connection within the deadlines and bounds of options. The head is looked for only in the bytes that arrived since the last read, a body of known length is appended to one buffer, and a chunked body is decoded as its chunks complete (a chunk still arriving is not looked at until all of it has), so the work is proportional to the bytes received, however they are split. The text is empty when the framing is refused, a chunked body is not complete when the stream ends, or a deadline ended the reading; a body of known length that the stream ended early is returned as far as it came.

serveHttpOnceWith (fun)

fun serveHttpOnceWith(router: HttpRouter, var listener: TcpListener, options: HttpServeOptions): int

Accepts one connection on listener, dispatches through router within the deadlines of options, writes the response, and closes the connection. Returns the bytes written, or -1 when the response was not written in full.

serveHttpOnce (fun)

fun serveHttpOnce(router: HttpRouter, var listener: TcpListener): int

Accepts one connection on listener, dispatches through router, writes the response, and closes the connection, with the deadlines of httpServeOptions().

serveHttpWith (fun)

fun serveHttpWith(router: HttpRouter, port: int, options: HttpServeOptions): int

Listens on port and serves requests through router with options until graceful shutdown. Returns the listener loop's status.

serveHttp (fun)

fun serveHttp(router: HttpRouter, port: int): int

Listens on port and serves requests through router, with the deadlines of httpServeOptions(), until graceful shutdown. Returns the listener loop's status.

serveHttpOnListenerWith (fun)

fun serveHttpOnListenerWith(router: HttpRouter, var listener: TcpListener, options: HttpServeOptions): int

Serves requests from listener through router with options until graceful shutdown. Sends only headers on HEAD requests, closes each client and the listener, and returns zero on graceful shutdown.

serveHttpOnListener (fun)

fun serveHttpOnListener(router: HttpRouter, var listener: TcpListener): int

Serves requests from listener through router with the deadlines of httpServeOptions() until graceful shutdown. Sends only headers on HEAD requests, closes each client and the listener, and returns zero on graceful shutdown.

httpRequestLineVersion (fun)

trusted fun httpRequestLineVersion(
    input: string, request: HttpRequest, headerEnd: int
): int

The request line must be method SP target SP HTTP/1.x and nothing else: returns 1 for HTTP/1.1, 0 for HTTP/1.0 and -1 for anything else, which is refused (a line that is not a request is never routed). The target is an origin form (/p), *, or an absolute form (http://host/p, which a proxy sends). The parser has already split the line, so this reads only where the version has to be: after the method, the path and the query. An absolute form must be http:// or https:// with a non-empty authority that is a host (no userinfo, space, comma or control byte): the servers then use that authority as the host and route by its path (httpRequestOriginForm, RFC 9112 3.2.2).

httpRequestOriginForm (fun)

fun httpRequestOriginForm(request: HttpRequest): HttpRequest

RFC 9112 3.2.2: a request whose target is an absolute form (http://host/p) is served as /p with the target's authority as its Host (any Host field it sent is replaced), so routes and a Host check see what a proxy routed by. Any other request is returned as it is. Call it after httpRequestLineVersion accepted the line.

Built from Abla v0.2.79 source ba5d6b7d. Examples and generated signatures follow that source revision.