ob:http (Serve & Fetch)¶
ob:http provides an async HTTP client (fetch) and a production-grade HTTP/1.1 & HTTP/2 server (serve) powered by Hyper 1.x and Tokio.
Required permission:
--allow-net(or scoped, e.g.--allow-net=127.0.0.1:3000,api.github.com).
http.serve(handler) / http.serve(opts, handler)¶
Starts an HTTP/1.1 (Keep-Alive, Chunked) and HTTP/2 server and invokes handler(req) for each incoming request.
Built-in Engine Features¶
- 1-argument 12-Factor mode:
http.serve(app:handler())automatically readshostandportfromHOST/PORTenv vars,config.toml, or defaults (127.0.0.1:3000). - Automatic Gzip compression: compresses text/HTML/JSON/CSS/JS responses automatically when the client sends
Accept-Encoding: gzip. - Body size protection: rejects payloads exceeding
max_body_size(default 10 MiB) with413 Payload Too Large. - Binary-safe bodies: supports binary uploads (
multipart/form-data) and binary responses (images, PDFs, downloads). - Multi-value headers: pass an array of strings as a header value (e.g. multiple
Set-Cookieheaders). - Graceful Shutdown: handles
Ctrl+C(SIGINT) cleanly, draining in-flight requests before exiting.
Options (opts)¶
Pass a port number (binds to 127.0.0.1), a table, or omit opts to use config.toml / env:
host(string, default fromHOST/config.toml/"127.0.0.1")port(number, default fromPORT/config.toml/3000)max_body_size(number, default10485760— 10 MiB)max_requests(number?, optional — handy for automated tests)
Request Object (req)¶
req.method—"GET","POST", etc.req.path— request path (e.g."/api/users").req.query— parsed query parameters table.req.query_string— raw query string.req.headers— lowercase header map.req.body— binary-safe request body string.req.remote_addr— client IP address (used byrouter.rate_limit()).
Handler Return Values¶
Your handler may return:
- A string (
200 OK, automatically setstext/htmlif it starts with<). - A
.luax/ob:htmlVNode (automatically rendered astext/html; charset=utf-8). - A response table
{ status = 200, headers = { ... }, body = "..." }.
local http = require("ob:http")
local json = require("ob:json")
-- Reads [server] from config.toml / HOST / PORT automatically:
http.serve(function(req)
if req.path == "/api/health" then
return {
status = 200,
headers = { ["Content-Type"] = "application/json" },
body = json.encode({ ok = true, runtime = "Orbita" }),
}
end
return { status = 404, body = "Not Found" }
end)
http.fetch(url, opts?)¶
Performs an async HTTP request using reqwest with native rustls TLS.