http
import http
A complete HTTP stack: a client, a server, and the pieces both are built from.
The server is meant to face the internet directly. Everything that is normally the reverse proxy’s job - TLS, static files with byte ranges and conditional requests, response compression, keep-alive, request size limits, timeouts, forwarding-header handling - is here rather than assumed to be somewhere in front.
Making a request
import http
echo http.get('https://example.com').as_text()
The module-level get(), post(), put(), patch(), delete(),
head(), options() and trace() all go through one shared client,
which keeps its connections open between calls. For anything that needs
its own settings - a base URL, an authorization header, a cookie jar, a
custom certificate authority
- build a client of your own:
var api = http.client('https://api.example.com', {
headers: { 'Authorization': 'Bearer ' + token },
})
var user = api.get('/users/me').raise_for_status().as_dict()
api.post('/posts', { title: 'Hello', body: 'World' })
Serving requests
import http
var server = http.server(3000)
server.get('/', @(request, response) {
response.html('<h1>Hello</h1>')
})
server.get('/users/:id', @(request, response) {
response.json({ id: request.param('id') })
})
server.serve_files('/static', './public', { cache_age: 86400 })
server.listen()
Routes match literal segments, :name parameters, and a trailing
catch-all, with the most specific pattern winning regardless of
registration order. use() adds middleware, which runs outermost first
and controls whether the rest of the chain runs at all:
server.use(@(request, response, next) {
if request.header('x-api-key') != key {
response.json({ error: 'unauthorized' }, 401)
return
}
next()
})
Serving over TLS
var server = http.server(443, '0.0.0.0')
server.load_certs('/etc/certs/site.crt', '/etc/certs/site.key')
server.listen()
Using more than one core
listen() serves connections on the calling thread. serve() runs the
same pipeline across a pool of isolates instead, one accept loop handing
connections to workers:
# app.zu
import http
def setup(server) {
server.get('/', @(request, response) {
response.text('hello from a worker')
})
}
# main.zu
import http
import .app
http.serve(app.setup, { port: 3000, workers: 8 })
setup runs inside each worker, so everything it reaches for has to be
something an isolate can be handed. A module is not: a setup that
names an imported module belongs in a module itself, which the isolate
resolves by name and whose own imports are resolved again on that side.
What the module handles for you
Requests are parsed strictly: a header name with whitespace before its
colon, two disagreeing Content-Length values, a Transfer-Encoding
alongside a Content-Length, an obsolete folded header line - each of
these is a way to make a proxy and an origin server disagree about where
one message ends and the next begins, and each is refused rather than
guessed at.
Bodies are decompressed on the way in and compressed on the way out, cookies are parsed and rendered per RFC 6265, dates are read in all three formats HTTP allows and written in the one it requires, and content negotiation follows the quality weights the client actually sent.
Sessions
http.session keeps per-visitor state on the server and finds it again
by a cookie:
import http.session
server.use(http.session.session())
server.get('/', @(request, response) {
var seen = request.session().get('seen', 0)
request.session().set('seen', seen + 1)
response.text('visit ${seen + 1}')
})
Sessions are kept in files by default, in a database through
http.session.sql, or anywhere else a SessionStore can reach.
The http API
Every public name in http, wherever it is declared. Each links to the
page that documents it.
| Name | Kind | Summary |
|---|---|---|
http.BodyReader | class | Reads a message body off a connection according to whichever of HTTP/1.1’s framings applies. |
http.ByteRange | class | One byte range asked for by a Range header, already resolved against the size of the representation. |
http.Connection | class | A buffered, message-oriented view of a connected socket. |
http.ConnectionError | class | Raised when a connection could not be established, or when an established connection failed or was closed… |
http.Cookie | class | A single cookie, in either direction: the name/value pair a client sends back in a Cookie header, or the… |
http.CookieJar | class | A client-side cookie store: keeps the cookies a server set, decides which of them a later request is entitled… |
http.Headers | class | An ordered, case-insensitive, multi-value collection of HTTP header fields. |
http.HttpClient | class | An HTTP client. |
http.HttpError | class | Base class for every error the http module raises. |
http.HttpRequest | class | An HTTP request, in both directions. |
http.HttpResponse | class | An HTTP response, in both directions: the thing a server builds and sends, and the thing a client receives… |
http.HttpServer | class | An HTTP/1.1 server. |
http.LoadBalancer | class | Balances requests across several upstreams. |
http.MultipartBuilder | class | Builds a multipart/form-data request body. |
http.MultipartData | class | The result of parsing a multipart/form-data body. |
http.ProtocolError | class | Raised when a peer sends something that isn’t a well-formed HTTP message: a broken request line or status… |
http.ReverseProxy | class | A reverse proxy: takes a request this server received and passes it to an upstream, then passes the… |
http.Route | class | One registered route. |
http.Router | class | Matches request paths to handlers. |
http.StaticFiles | class | Serves files from a directory, with the conditional-request, range-request and caching behaviour a browser… |
http.StatusError | class | Raised by HttpResponse.raise_for_status() when the response carries a 4xx or 5xx status. |
http.TimeoutError | class | Raised when an operation exceeded its configured deadline: a connect, a read, a write, or the total time… |
http.TooLargeError | class | Raised when a message exceeds one of the configured size limits - request line, header block, or body. |
http.TooManyRedirectsError | class | Raised by the client when a redirect chain exceeds HttpClient.max_redirects, which usually means the chain… |
http.UnsupportedProtocolError | class | Raised when a URL names a scheme this module cannot speak, or when a peer insists on a protocol version that… |
http.UploadedFile | class | One file received in a multipart/form-data body. |
http.WebSocket | class | An open WebSocket connection (RFC 6455). |
http.body.DEFAULT_BROTLI_QUALITY | constant | The brotli quality this module compresses a response with when the caller names no quality of its own. |
http.body.decode_content | function | Reverses the content codings named in a Content-Encoding field, innermost last, as RFC 9110 §8.4 requires. |
http.body.encode_chunk | function | Wraps data as a single HTTP/1.1 chunk: the size in hexadecimal, a CRLF, the data, and a CRLF. |
http.body.encode_content | function | Applies a content coding to data. |
http.body.encode_last_chunk | function | The terminating 0\r\n chunk plus a trailer section. |
http.body.parse_chunk_size | function | Parses a chunk-size line, ignoring any chunk extensions after the ;. |
http.body.parse_content_length | function | Parses a Content-Length field value. |
http.body.reader_for | function | Works out how a message’s body is framed and returns a reader for it. |
http.build_query_string | function | Encodes parameters as an application/x-www-form-urlencoded string. |
http.client | function | Builds a new HttpClient. |
http.cookies.format_cookie_header | function | Renders a dictionary of name to value as a request Cookie header value. |
http.cookies.is_valid_value | function | Whether value can be sent as a cookie value without quoting. |
http.cookies.parse_cookie_header | function | Parses a request’s Cookie header into a dictionary of name to value. |
http.cookies.parse_set_cookie | function | Parses one Set-Cookie field value into a Cookie. |
http.delete | function | Sends a DELETE request through the shared client. |
http.files.etag_matches | function | Whether an If-None-Match value matches etag. |
http.files.parse_range | function | Parses a Range header against a representation of size bytes. |
http.files.weak_etag | function | A weak validator derived from a file’s size and modification time. |
http.get | function | Sends a GET request through the shared client. |
http.h1.ChunkWriter | class | The writer handed to a streaming response body. |
http.h1.DEFAULT_LIMITS | constant | |
http.h1.SERVER_NAME | constant | |
http.h1.USER_AGENT | constant | |
http.h1.parse_version | function | Parses HTTP/1.1 into '1.1', rejecting anything that is not a version this module understands the framing… |
http.h1.read_request | function | Reads one request off a connection: the request line, the header section, and enough framing information to… |
http.h1.read_response | function | Reads a response off a connection. |
http.h1.send_continue | function | Sends a 100 Continue interim response, telling a client that asked with Expect: 100-continue to go ahead… |
http.h1.should_keep_alive | function | Whether the connection should be kept open after this exchange. |
http.h1.write_request | function | Writes a request to a connection. |
http.h1.write_response | function | Writes a response to a connection and returns whether the connection is still usable afterwards. |
http.h2.Http2Connection | class | An HTTP/2 connection, in either role. |
http.h2.Http2Stream | class | One HTTP/2 stream: a request and its response, multiplexed with others over a single connection. |
http.h2.Http2Writer | class | The writer a streaming response body gets on an HTTP/2 connection. |
http.h2.frames.CANCEL | constant | CANCEL. |
http.h2.frames.COMPRESSION_ERROR | constant | COMPRESSION_ERROR. |
http.h2.frames.CONNECT_ERROR | constant | CONNECT_ERROR. |
http.h2.frames.CONTINUATION | constant | CONTINUATION frame. |
http.h2.frames.DATA | constant | DATA frame. |
http.h2.frames.ENHANCE_YOUR_CALM | constant | ENHANCE_YOUR_CALM. |
http.h2.frames.FLAG_ACK | constant | ACK flag, on SETTINGS and PING. |
http.h2.frames.FLAG_END_HEADERS | constant | END_HEADERS flag, on HEADERS, PUSH_PROMISE and CONTINUATION. |
http.h2.frames.FLAG_END_STREAM | constant | END_STREAM flag, on DATA and HEADERS. |
http.h2.frames.FLAG_PADDED | constant | PADDED flag, on DATA, HEADERS and PUSH_PROMISE. |
http.h2.frames.FLAG_PRIORITY | constant | PRIORITY flag, on HEADERS. |
http.h2.frames.FLOW_CONTROL_ERROR | constant | FLOW_CONTROL_ERROR. |
http.h2.frames.FRAME_SIZE_ERROR | constant | FRAME_SIZE_ERROR. |
http.h2.frames.Frame | class | One frame, as read off the wire. |
http.h2.frames.GOAWAY | constant | GOAWAY frame. |
http.h2.frames.HEADERS | constant | HEADERS frame. |
http.h2.frames.HTTP_1_1_REQUIRED | constant | HTTP_1_1_REQUIRED. |
http.h2.frames.INADEQUATE_SECURITY | constant | INADEQUATE_SECURITY. |
http.h2.frames.INTERNAL_ERROR | constant | INTERNAL_ERROR. |
http.h2.frames.NO_ERROR | constant | NO_ERROR. |
http.h2.frames.PING | constant | PING frame. |
http.h2.frames.PREFACE | constant | The connection preface every HTTP/2 client sends before anything else. |
http.h2.frames.PRIORITY | constant | PRIORITY frame; deprecated by RFC 9113 and ignored here. |
http.h2.frames.PROTOCOL_ERROR | constant | PROTOCOL_ERROR. |
http.h2.frames.PUSH_PROMISE | constant | PUSH_PROMISE frame. |
http.h2.frames.REFUSED_STREAM | constant | REFUSED_STREAM. |
http.h2.frames.RST_STREAM | constant | RST_STREAM frame. |
http.h2.frames.SETTINGS | constant | SETTINGS frame. |
http.h2.frames.SETTINGS_ENABLE_PUSH | constant | SETTINGS_ENABLE_PUSH. |
http.h2.frames.SETTINGS_HEADER_TABLE_SIZE | constant | SETTINGS_HEADER_TABLE_SIZE. |
http.h2.frames.SETTINGS_INITIAL_WINDOW_SIZE | constant | SETTINGS_INITIAL_WINDOW_SIZE. |
http.h2.frames.SETTINGS_MAX_CONCURRENT_STREAMS | constant | SETTINGS_MAX_CONCURRENT_STREAMS. |
http.h2.frames.SETTINGS_MAX_FRAME_SIZE | constant | SETTINGS_MAX_FRAME_SIZE. |
http.h2.frames.SETTINGS_MAX_HEADER_LIST_SIZE | constant | SETTINGS_MAX_HEADER_LIST_SIZE. |
http.h2.frames.SETTINGS_TIMEOUT | constant | SETTINGS_TIMEOUT. |
http.h2.frames.STREAM_CLOSED | constant | STREAM_CLOSED. |
http.h2.frames.WINDOW_UPDATE | constant | WINDOW_UPDATE frame. |
http.h2.frames.decode_settings | function | Parses a SETTINGS payload into a dictionary. |
http.h2.frames.encode_error | function | Builds an RST_STREAM payload. |
http.h2.frames.encode_goaway | function | Builds a GOAWAY payload. |
http.h2.frames.encode_settings | function | Builds a SETTINGS payload from a dictionary of identifier to value. |
http.h2.frames.read_frame | function | Reads one frame off a connection. |
http.h2.frames.read_u24 | function | Reads a 24-bit big-endian integer from data at offset. |
http.h2.frames.read_u32 | function | Reads a 32-bit big-endian integer from data at offset. |
http.h2.frames.write_frame | function | Writes one frame to a connection. |
http.h2.frames.write_u32 | function | Appends a 32-bit big-endian integer to out. |
http.h2.hpack.Decoder | class | Decodes header blocks for one direction of one connection. |
http.h2.hpack.DynamicTable | class | The dynamic table half of an HPACK context: the most recently inserted fields, evicted from the far end when… |
http.h2.hpack.Encoder | class | Encodes header blocks for one direction of one connection. |
http.h2.hpack.decode_integer | function | Decodes an integer with an prefix_bits-wide prefix, starting at offset. |
http.h2.hpack.decode_string | function | Decodes a string literal starting at offset. |
http.h2.hpack.encode_integer | function | Encodes an integer with an prefix_bits-wide prefix, per RFC 7541 §5.1. |
http.h2.hpack.encode_string | function | Encodes a string literal, Huffman-coding it when that comes out shorter. |
http.h2.huffman.EOS | constant | The number of the symbol HPACK uses to pad the final byte of a Huffman-encoded string, and which must never… |
http.h2.huffman.decode | function | Decodes a Huffman-encoded string. |
http.h2.huffman.encode | function | Huffman-encodes data, padding the final byte with the leading bits of the EOS code (which are all ones) as… |
http.h2.huffman.encoded_length | function | The number of bytes data would occupy once Huffman-encoded. |
http.head | function | Sends a HEAD request through the shared client. |
http.headers.canonical_name | function | The conventional spelling of a field name, e.g. 'content-type' becomes 'Content-Type' and 'etag'… |
http.headers.is_never_folded | function | Whether a field with this name must be repeated rather than folded into one comma-separated value when… |
http.headers.is_valid_name | function | Whether name is a syntactically valid HTTP field name, i.e. a non-empty RFC 9110 token. |
http.headers.is_valid_value | function | Whether value is a legal HTTP field value. |
http.headers.parse | function | Parses a raw header block - everything between a start line and the blank line that ends the head - into a… |
http.middleware.basic_auth | function | Requires HTTP Basic authentication. |
http.middleware.bearer_auth | function | Requires a bearer token. |
http.middleware.cors | function | Answers CORS preflights and adds the cross-origin headers a browser needs before it will let script read a… |
http.middleware.etag | function | Computes a weak ETag over a finished response body and answers 304 Not Modified when the client already… |
http.middleware.force_https | function | Sends every request that arrived over cleartext to the same URL over HTTPS. |
http.middleware.jwt_auth | function | Requires a valid JSON Web Token, verified by the jwt module. |
http.middleware.logger | function | Writes one line per request once the response is finished. |
http.middleware.parse_basic | function | Parses an HTTP Basic Authorization header into a username and password. |
http.middleware.parse_bearer | function | Parses a Bearer Authorization header into its token. |
http.middleware.rate_limit | function | Limits how many requests one client may make in a window of time. |
http.middleware.request_id | function | Attaches a unique identifier to every request, echoing back one the client supplied so a trace can be… |
http.middleware.security_headers | function | Adds the response headers a browser acts on to harden a page. |
http.multipart.parse | function | Parses a multipart/form-data body (RFC 7578). |
http.negotiate.AcceptEntry | class | One entry of an Accept-style header: the value, its quality weight, and any other parameters it carried. |
http.negotiate.best_match | function | Picks the entry of available the client would most like, or nil when it would accept none of them. |
http.negotiate.names_explicitly | function | Whether header names value outright rather than covering it with a wildcard. |
http.negotiate.parse_accept | function | Parses an Accept, Accept-Encoding, Accept-Language or Accept-Charset header into entries, most… |
http.negotiate.preferred_encoding | function | Picks a content coding for a response, given the request’s Accept-Encoding. |
http.negotiate.preferred_language | function | Picks a language from available using the request’s Accept-Language. |
http.negotiate.quality_of | function | The quality weight header assigns to candidate, honouring wildcards. |
http.options | function | Sends an OPTIONS request through the shared client. |
http.parse_query_string | function | Decodes an application/x-www-form-urlencoded string - a query string, or a form body - into `name ->… |
http.patch | function | Sends a PATCH request through the shared client. |
http.post | function | Sends a POST request through the shared client. |
http.put | function | Sends a PUT request through the shared client. |
http.router.RouteMatch | class | The result of asking a router about a request. |
http.serve | function | Runs a server across a pool of isolates, one per core by default. |
http.server | function | Builds an HttpServer. |
http.session.FORMAT | constant | The payload format this module writes and reads. |
http.session.FileStore | class | Keeps each session in its own file, named after the session’s storage key. |
http.session.ID_LENGTH | constant | How many characters a session identifier has. |
http.session.MemoryStore | class | Keeps sessions in a dictionary, for as long as the isolate that made the store lives. |
http.session.Session | class | One visitor’s session. |
http.session.SessionError | class | Raised when a session cannot be read, written or configured: a storage directory that cannot be created or is… |
http.session.SessionStore | class | What every session store implements. |
http.session.default_directory | function | The directory sessions are kept in when a FileStore is not told where to put them: a private subdirectory… |
http.session.file.DIRECTORY_MODE | constant | |
http.session.file.FILE_MODE | constant | |
http.session.file.SUFFIX | constant | |
http.session.session | function | Middleware that finds each request’s session and writes it back when the response goes out. |
http.session.sql.DEFAULT_TABLE | constant | |
http.session.sql.SqlStore | class | Keeps sessions in one table of a relational database. |
http.session.storage_key | function | The key a store files a session under: the SHA-256 of the session identifier, as 64 lowercase hex characters. |
http.set_headers | function | Sets the default headers on the shared client and returns it, so a call can be chained straight onto it. |
http.shared_client | function | The shared client the module-level request functions use. |
http.sse.EventStream | class | The writer a server-sent event stream hands to its producer. |
http.sse.last_event_id | function | The Last-Event-ID a reconnecting client sent, or nil. |
http.sse.parse | function | Parses a text/event-stream body into a list of events, each a dictionary with event, data, id and… |
http.sse.stream | function | Turns response into a server-sent event stream and runs producer against it. |
http.status.ACCEPTED | constant | 202 Accepted. |
http.status.ALREADY_REPORTED | constant | 208 Already Reported (WebDAV, RFC 5842). |
http.status.BAD_GATEWAY | constant | 502 Bad Gateway. |
http.status.BAD_REQUEST | constant | 400 Bad Request. |
http.status.CONFLICT | constant | 409 Conflict. |
http.status.CONTENT_TOO_LARGE | constant | 413 Content Too Large. |
http.status.CONTINUE | constant | 100 Continue. |
http.status.CREATED | constant | 201 Created. |
http.status.EARLY_HINTS | constant | 103 Early Hints (RFC 8297). |
http.status.EXPECTATION_FAILED | constant | 417 Expectation Failed. |
http.status.FAILED_DEPENDENCY | constant | 424 Failed Dependency (WebDAV, RFC 4918). |
http.status.FORBIDDEN | constant | 403 Forbidden. |
http.status.FOUND | constant | 302 Found. |
http.status.GATEWAY_TIMEOUT | constant | 504 Gateway Timeout. |
http.status.GONE | constant | 410 Gone. |
http.status.HTTP_VERSION_NOT_SUPPORTED | constant | 505 HTTP Version Not Supported. |
http.status.IM_A_TEAPOT | constant | 418 I’m a teapot (RFC 2324). |
http.status.IM_USED | constant | 226 IM Used (RFC 3229). |
http.status.INSUFFICIENT_STORAGE | constant | 507 Insufficient Storage (WebDAV, RFC 4918). |
http.status.INTERNAL_SERVER_ERROR | constant | 500 Internal Server Error. |
http.status.LENGTH_REQUIRED | constant | 411 Length Required. |
http.status.LOCKED | constant | 423 Locked (WebDAV, RFC 4918). |
http.status.LOOP_DETECTED | constant | 508 Loop Detected (WebDAV, RFC 5842). |
http.status.METHOD_NOT_ALLOWED | constant | 405 Method Not Allowed. |
http.status.MISDIRECTED_REQUEST | constant | 421 Misdirected Request. |
http.status.MOVED_PERMANENTLY | constant | 301 Moved Permanently. |
http.status.MULTIPLE_CHOICES | constant | 300 Multiple Choices. |
http.status.MULTI_STATUS | constant | 207 Multi-Status (WebDAV, RFC 4918). |
http.status.NETWORK_AUTHENTICATION_REQUIRED | constant | 511 Network Authentication Required (RFC 6585). |
http.status.NON_AUTHORITATIVE_INFORMATION | constant | 203 Non-Authoritative Information. |
http.status.NOT_ACCEPTABLE | constant | 406 Not Acceptable. |
http.status.NOT_EXTENDED | constant | 510 Not Extended (RFC 2774). |
http.status.NOT_FOUND | constant | 404 Not Found. |
http.status.NOT_IMPLEMENTED | constant | 501 Not Implemented. |
http.status.NOT_MODIFIED | constant | 304 Not Modified. |
http.status.NO_CONTENT | constant | 204 No Content. |
http.status.OK | constant | 200 OK. |
http.status.PARTIAL_CONTENT | constant | 206 Partial Content. |
http.status.PAYMENT_REQUIRED | constant | 402 Payment Required. |
http.status.PERMANENT_REDIRECT | constant | 308 Permanent Redirect. |
http.status.PRECONDITION_FAILED | constant | 412 Precondition Failed. |
http.status.PRECONDITION_REQUIRED | constant | 428 Precondition Required (RFC 6585). |
http.status.PROCESSING | constant | 102 Processing (WebDAV, RFC 2518). |
http.status.PROXY_AUTHENTICATION_REQUIRED | constant | 407 Proxy Authentication Required. |
http.status.RANGE_NOT_SATISFIABLE | constant | 416 Range Not Satisfiable. |
http.status.REQUEST_HEADER_FIELDS_TOO_LARGE | constant | 431 Request Header Fields Too Large (RFC 6585). |
http.status.REQUEST_TIMEOUT | constant | 408 Request Timeout. |
http.status.RESET_CONTENT | constant | 205 Reset Content. |
http.status.SEE_OTHER | constant | 303 See Other. |
http.status.SERVICE_UNAVAILABLE | constant | 503 Service Unavailable. |
http.status.SWITCHING_PROTOCOLS | constant | 101 Switching Protocols. |
http.status.TEMPORARY_REDIRECT | constant | 307 Temporary Redirect. |
http.status.TOO_EARLY | constant | 425 Too Early (RFC 8470). |
http.status.TOO_MANY_REQUESTS | constant | 429 Too Many Requests (RFC 6585). |
http.status.UNAUTHORIZED | constant | 401 Unauthorized. |
http.status.UNAVAILABLE_FOR_LEGAL_REASONS | constant | 451 Unavailable For Legal Reasons (RFC 7725). |
http.status.UNPROCESSABLE_CONTENT | constant | 422 Unprocessable Content. |
http.status.UNSUPPORTED_MEDIA_TYPE | constant | 415 Unsupported Media Type. |
http.status.UPGRADE_REQUIRED | constant | 426 Upgrade Required. |
http.status.URI_TOO_LONG | constant | 414 URI Too Long. |
http.status.USE_PROXY | constant | 305 Use Proxy. |
http.status.VARIANT_ALSO_NEGOTIATES | constant | 506 Variant Also Negotiates (RFC 2295). |
http.status.is_bodiless | function | Whether a response carrying code is defined to have no body at all, regardless of what headers say. |
http.status.is_client_error | function | Whether code is a 4xx client error. |
http.status.is_error | function | Whether code is any kind of error, client or server. |
http.status.is_informational | function | Whether code is a 1xx interim status. |
http.status.is_redirect | function | Whether code is a 3xx redirection status. |
http.status.is_registered | function | Whether code is a registered status code with a canonical reason phrase of its own. |
http.status.is_server_error | function | Whether code is a 5xx server error. |
http.status.is_success | function | Whether code is a 2xx success status. |
http.status.preserves_method | function | Whether a redirect with code must keep the original method and body when followed. |
http.status.reason | function | The canonical reason phrase for code, e.g. 'Not Found' for 404. |
http.stream.accept | function | Turns a freshly accepted TcpStream into a Connection, running a server-side TLS handshake first when… |
http.stream.connect | function | Opens a connection to host on port, optionally wrapping it in TLS. |
http.stream.is_timeout_error | function | Whether a transport error message describes a timeout (or a would-block, which a socket with a receive… |
http.stream.tunnel | function | Opens a connection to host:port through an HTTP proxy’s CONNECT tunnel, running a TLS handshake with… |
http.tls_server | function | Builds an HttpServer already configured for TLS. |
http.trace | function | Sends a TRACE request through the shared client. |
http.util.find_bytes | function | Finds the first occurrence of the byte sequence needle in haystack, at or after from, or -1 when it… |
http.util.format_date | function | Formats a Unix timestamp as an IMF-fixdate, the one date format RFC 9110 §5.6.7 requires every HTTP sender to… |
http.util.is_valid_method | function | Whether value is a valid HTTP method: a non-empty token, per RFC 9110 §9. |
http.util.normalize_path | function | Resolves the . and .. segments of a path and collapses repeated slashes, returning a path that cannot… |
http.util.parse_basic | function | Parses an HTTP Basic Authorization field value into a username and password. |
http.util.parse_bearer | function | Parses a Bearer Authorization field value into its token. |
http.util.parse_date | function | Parses any of the three date formats RFC 9110 §5.6.7 requires a recipient to accept, and returns the Unix… |
http.util.parse_parameters | function | Splits a header value that carries parameters - a media type, a Content-Disposition, a challenge - into its… |
http.util.percent_decode | function | Percent-decodes a URI component, turning + into a space only when plus_as_space is set - which is right… |
http.util.percent_encode | function | Percent-encodes every character of text that is not an RFC 3986 unreserved character, over the UTF-8… |
http.util.quote | function | Wraps value in double quotes, escaping any quote or backslash it contains, so it can be used as an RFC 9110… |
http.util.random_token | function | A random lowercase-hex token of length characters, drawn from the platform’s cryptographically secure… |
http.util.secure_equals | function | Compares two strings without leaking, through how long the comparison takes, where they first differ. |
http.util.to_hex | function | n as lowercase hexadecimal, with no 0x prefix and no padding. |
http.util.unquote | function | Removes the surrounding double quotes from a header value and resolves its backslash escapes. |
http.websocket.CLOSE_GOING_AWAY | constant | The endpoint is going away. |
http.websocket.CLOSE_INTERNAL_ERROR | constant | An unexpected condition on the server. |
http.websocket.CLOSE_INVALID_PAYLOAD | constant | A text message that was not valid UTF-8. |
http.websocket.CLOSE_NORMAL | constant | Normal closure. |
http.websocket.CLOSE_POLICY_VIOLATION | constant | A message that violates a policy. |
http.websocket.CLOSE_PROTOCOL_ERROR | constant | A protocol error was detected. |
http.websocket.CLOSE_TOO_LARGE | constant | A message too large to process. |
http.websocket.CLOSE_UNSUPPORTED | constant | A message of a kind this endpoint cannot accept. |
http.websocket.Message | class | One complete WebSocket message, with any fragmentation already reassembled. |
http.websocket.OPCODE_BINARY | constant | Binary frame. |
http.websocket.OPCODE_CLOSE | constant | Close frame. |
http.websocket.OPCODE_CONTINUATION | constant | Continuation frame. |
http.websocket.OPCODE_PING | constant | Ping frame. |
http.websocket.OPCODE_PONG | constant | Pong frame. |
http.websocket.OPCODE_TEXT | constant | Text frame. |
http.websocket.accept | function | Completes a WebSocket handshake and takes over the connection. |
http.websocket.accept_key | function | The value a server must return in Sec-WebSocket-Accept for a given client key. |
http.websocket.connect | function | Opens a WebSocket connection to target. |
http.websocket.is_handshake | function | Whether request is a well-formed WebSocket handshake. |
http.worker.serve | function | Binds a listening socket and serves it across a pool of worker isolates. |
http.worker.worker_main | function | The loop each worker isolate runs: build a server of its own from setup, then serve whatever connections… |
Submodules
| Module | Reached as | Summary |
|---|---|---|
http.body | http.body.* | A request or response body, in whatever shape the wire delivered it: a fixed Content-Length, a chunked… |
http.client | http.client.* | HttpClient: the connection-pooling, redirect-following, cookie-aware side of the module. |
http.cookies | http.cookies.* | Cookies, both halves of them: Cookie is one cookie with its attributes, CookieJar is a store that applies… |
http.errors | http.* | Every error the HTTP stack raises, under one root. |
http.files | http.files.* | Serving files off disk, with the parts that make it correct rather than merely working: conditional requests,… |
http.h1 | http.h1.* | HTTP/1.1 on the wire (RFC 9110 and RFC 9112): reading a request line and its headers, writing a status line… |
http.h2 | http.h2.* | HTTP/2 (RFC 9113) and the header compression it uses (RFC 7541). |
http.headers | http.headers.* | Headers: a case-insensitive, order-preserving multimap, because HTTP header names do not compare… |
http.middleware | http.middleware.* | The middleware every public HTTP service ends up needing: CORS, access logging, the security headers a… |
http.multipart | http.multipart.* | multipart/form-data, in both directions. |
http.negotiate | http.negotiate.* | Content negotiation: choosing what to send when the client has said what it prefers. |
http.proxy | http.proxy.* | ReverseProxy forwards a request to another server and streams the response back; LoadBalancer spreads… |
http.request | http.request.* | HttpRequest: one inbound request, with its method, target, headers and body, plus the query string and… |
http.response | http.response.* | HttpResponse: one response, whether it is being built by a handler or read back from a server. |
http.router | http.router.* | Matching a request to a handler. |
http.server | http.server.* | HttpServer: the server end of the module. |
http.session | http.session.* | Server-side sessions: a small amount of state that belongs to one visitor, kept on the server and found again… |
http.sse | http.sse.* | Server-sent events (the WHATWG text/event-stream format): a one-way stream of named, identified messages… |
http.status | http.status.* | The HTTP status codes registered with IANA, their canonical reason phrases, and a handful of predicates for… |
http.stream | http.stream.* | The transport underneath everything else: a byte stream with buffering, timeouts and optional TLS. |
http.util | http.util.* | The small, exact pieces of the HTTP specifications that several parts of the module need: date formatting,… |
http.websocket | http.websocket.* | WebSocket (RFC 6455), both ends of it. |
http.worker | http.worker.* | The multi-process side of HttpServer: a pool of isolates, each accepting and serving connections from the… |
Functions
shared_client()
http.shared_client() -> HttpClient
The shared client the module-level request functions use.
Reach for this to change a setting that should apply to every casual
http.get() in a program - a proxy-wide certificate authority, a longer
timeout - and build your own client() for anything more specific than
that.
Returns HttpClient
client()
http.client(base_url: ?string, options: ?dict) -> HttpClient
Builds a new HttpClient.
Parameters
base_url(?string) — prefixed to any relative request targetoptions(?dict) — anyHttpClientfield, plusheaders
Returns HttpClient
set_headers()
http.set_headers(values: dict) -> HttpClient
Sets the default headers on the shared client and returns it, so a call can be chained straight onto it.
echo http.set_headers({ 'Authorization': 'Bearer ' + token })
.get('https://example.com/me')
.as_dict()
Parameters
values(dict)
Returns HttpClient
get()
http.get(url: string, options: ?dict) -> HttpResponse
Sends a GET request through the shared client.
Parameters
url(string)options(?dict) — seeHttpClient.request()
Returns HttpResponse
post()
http.post(url: string, data, options: ?dict) -> HttpResponse
Sends a POST request through the shared client.
Parameters
url(string)data(?any) — a string or bytes sent as-is, a dictionary or list sent as JSON, or aMultipartBuilderoptions(?dict)
Returns HttpResponse
put()
http.put(url: string, data, options: ?dict) -> HttpResponse
Sends a PUT request through the shared client.
Parameters
url(string)data(?any)options(?dict)
Returns HttpResponse
patch()
http.patch(url: string, data, options: ?dict) -> HttpResponse
Sends a PATCH request through the shared client.
Parameters
url(string)data(?any)options(?dict)
Returns HttpResponse
delete()
http.delete(url: string, options: ?dict) -> HttpResponse
Sends a DELETE request through the shared client.
Parameters
url(string)options(?dict)
Returns HttpResponse
head()
http.head(url: string, options: ?dict) -> HttpResponse
Sends a HEAD request through the shared client. Redirects are not
followed unless options says to.
Parameters
url(string)options(?dict)
Returns HttpResponse
options()
http.options(url: string, options: ?dict) -> HttpResponse
Sends an OPTIONS request through the shared client.
Parameters
url(string)options(?dict)
Returns HttpResponse
trace()
http.trace(url: string, options: ?dict) -> HttpResponse
Sends a TRACE request through the shared client.
Parameters
url(string)options(?dict)
Returns HttpResponse
server()
http.server(port: ?number, host: ?string) -> HttpServer
Builds an HttpServer.
Parameters
port(?number) — defaults to8000host(?string) — defaults to'127.0.0.1'
Returns HttpServer
tls_server()
http.tls_server(port: number, cert_chain: string, private_key: string, host: ?string) -> HttpServer
Builds an HttpServer already configured for TLS.
Parameters
port(number)cert_chain(string) — the PEM certificate chain, leaf firstprivate_key(string) — the PEM private keyhost(?string)
Returns HttpServer
serve()
http.serve(setup, options: ?dict)
Runs a server across a pool of isolates, one per core by default.
setup is called once inside each worker with that worker’s own
HttpServer, and registers the routes, middleware and settings the
worker should serve with. It may be defined in the main script or in a
module, and may use whatever it imports; an imported module is reloaded
inside the worker rather than shared with it, so the worker gets its own
copy of that module’s top-level state.
The calling isolate binds the socket and accepts connections, handing each one to a worker. It does not return until the server is stopped.
Parameters
setup(function(1)) — receives the worker’sHttpServeroptions(?dict) —port(default8000),host(default'127.0.0.1'),workers(default: the number of CPUs),backlog(how many accepted connections may wait for a free worker), pluscert_chain/private_keyfor TLS
Raises HttpError if the socket cannot be bound
2026, Richard Ore and Zuri contributors