radlang — HTTP (http & httpserver)
This document covers radlang’s built-in HTTP support: the http namespace
for making client requests, and the httpserver namespace for building
servers with routing, middleware, and CORS.
For language fundamentals see the Overview.
Overview
Both namespaces are compiler-intrinsic — the names http and httpserver
are reserved and dispatched directly to the runtime, so they need no
import.
fn main() {
// Client: fetch a URL (synchronous twin — see "Async by default" below)
HttpResponse res = http.getSync("http://example.com")
sys.output(res.status.toString()) // 200
sys.output(res.body)
}Several built-in types support this API:
| Type | Role |
|---|---|
HttpResponse |
Result of a client request / value a handler returns |
HttpRequest |
The incoming request passed to a server handler |
HttpServer |
An opaque server handle from httpserver.serve |
NextFn |
Arg-less next() callback in middleware; advances the chain |
The HTTP client (http)
http.get(url, headers?) : Future<HttpResponse>
http.delete(url, headers?) : Future<HttpResponse>
http.post(url, body, headers?) : Future<HttpResponse>
http.put(url, body, headers?) : Future<HttpResponse>
http.patch(url, body, headers?) : Future<HttpResponse>
http.request(method, url, headers, body) : Future<HttpResponse>Every verb takes an optional trailing headers argument — either a
string[] of "Name: value" lines or a Map<string,string> (see
maps); {} means no extra headers. Content-Type is just a header — there is no separate
content-type argument; set it in the headers when a request needs one:
http.getSync(url, ["Authorization: Bearer abc123"])
http.getSync(url, { "Authorization": "Bearer abc123", "Accept": "application/json" })
http.postSync(url, body, { "Content-Type": "application/json", "X-Trace": "42" }) Async by default
The request verbs are asynchronous by default — each runs the round-trip on
a worker thread and returns a Future<HttpResponse>, so a busy server or
scheduler is never blocked waiting on a socket. Consume the future with await
(inside an async fn) or .resolve(cb) (a non-blocking microtask callback):
async fn fetchTitle(): string {
HttpResponse res = await http.get("http://example.com")
return res.body
}Each verb has a synchronous …Sync twin — getSync, postSync, putSync,
patchSync, deleteSync, requestSync — that blocks and returns the
HttpResponse directly. Use the twins in straight-line scripts; the examples in
this section use them for brevity.
Every response is an HttpResponse with these fields:
| Field | Type | Meaning |
|---|---|---|
status |
int | HTTP status code (e.g. 200) |
body |
string | Response body |
contentType |
string | The response Content-Type (a convenience reader for the Content-Type header) |
Client responses also capture all response headers off the wire, read via methods (case-insensitive):
HttpResponse r = http.getSync(url)
r.header("ETag") // string ("" if absent)
r.hasHeader("Set-Cookie") // bool
r.headerAll("Set-Cookie") // string[] — every value of a repeated header
r.headers() // string[] — every "Name: value" linefn main() {
// GET (sync twin)
HttpResponse r = http.getSync("http://localhost:8080/hello")
if r.status == 200 {
sys.output(r.body)
}
// POST with a body + content type (a header)
HttpResponse p = http.postSync("http://localhost:8080/echo", "payload",
{ "Content-Type": "text/plain" })
sys.output(p.body)
// DELETE
http.deleteSync("http://localhost:8080/item/1")
}Set an outgoing Content-Type (or any header) through the headers argument —
it is just a header like any other.
For full control over the method, http.request / http.requestSync take the
headers as a string[] of "Name: value" lines:
fn main() {
string[] headers = ["Authorization: Bearer abc123", "Accept: application/json"]
HttpResponse r = http.requestSync("GET", "http://localhost:8080/me", headers, "")
sys.output(r.status.toString())
} URL encoding
Two helpers percent-encode / percent-decode strings for use in URLs and query
strings (the RFC 3986 unreserved set A–Z a–z 0–9 - _ . ~ is left untouched;
decoding also turns + into a space):
http.encode(s: string) : string // "a b/c" -> "a%20b%2Fc"
http.decode(s: string) : string // "a%20b" -> "a b" Timeouts and transport errors
Every request has a connect + transfer timeout (default 30 seconds). Bound it for all subsequent requests with:
http.timeout(seconds: int) : void // e.g. http.timeout(5)http.timeout overrides the default for the rest of the run. To change the
default itself without code, bake it into the executable with
runtime.httpTimeoutS in config.yaml (whole seconds, default 30, range 1 to
2147483647; an out-of-range value is clamped):
runtime:
httpTimeoutS: 10A transport failure — connection refused, DNS resolution failure, TLS error, or a timeout — never crashes or hangs the program:
On the synchronous (
…Sync) path it raises a catchableErrorwhosemessagedescribes the failure and whosecodeis the underlying transport error code. Wrap the call intry/catch:http.timeout(5) try { HttpResponse r = http.getSync("http://localhost:1/health") sys.output(r.body) } catch (Error e) { sys.output("request failed: " + e.message) }On the async path (
await http.get(...)/.resolve) the future resolves to anHttpResponsewithstatus == 0and the failure message inbody(throwing from the scheduler’s completion tick would unwind the wrong frame, so the failure is delivered as a value). Checkstatus != 0before using it, or use the…Synctwin inside atry/catchwhen you want a throw.
Resilience (retry, circuit breaker, proxy)
Client resilience is configured process-wide and applies to every subsequent request (sync and async alike). All three are optional; the defaults leave behaviour unchanged.
http.retry(count: int, backoffMs: int = 200) : void
http.circuitBreaker(threshold: int, cooldownMs: int) : void
http.proxy(url: string) : void // "" disablesretry— retry failed requests up tocountextra times with exponential backoff (backoffMs * 2^(attempt-1)). A request is retried on a transport error or a5xxresponse;4xxand2xxare returned immediately. With the defaultcountof 0, retries are off.http.retry(3) // up to 3 retries, 200ms/400ms/800ms backoff http.retry(2, 50) // up to 2 retries, 50ms/100ms backoffcircuitBreaker— per-host failure tracking. Afterthresholdconsecutive failures (transport error or5xx) to a host, the circuit opens and further requests to that host fail fast with acircuit breaker openerror forcooldownMs. It then half-opens to allow one probe; a success closes it, a failure re-opens it. Off unlessthreshold > 0.http.circuitBreaker(5, 10000) // open after 5 fails, 10s cooldownproxy— route all requests through an HTTP proxy. Pass""to clear.http.proxy("http://127.0.0.1:8888")
Connections reuse a shared DNS cache across requests automatically (no configuration), avoiding repeat lookups to the same host.
On Android
Android ships no libcurl, so on --target android the client runs over the
platform’s HttpURLConnection (through JNI on framework classes; native syn
apps need no Java code for it). The API, the response fields and headers, the
redirect and streaming clients, retry, circuitBreaker and proxy behave as
above, and transport failures carry libcurl’s codes and messages (7
“Couldn’t connect to server”, 6 “Couldn’t resolve host name”, 28 “Timeout
was reached”, 60 for an untrusted certificate, …). TLS, certificates, the
system proxy and connection pooling come from Android. Differences:
- Cleartext
http://is blocked by Android’s network security policy for apps targeting API 28 and later. Such a request fails with code1and a message saying so; setbuild.android.cleartextTraffic: truein config.yaml to allow it (it applies to the whole app, WebView included).https://needs nothing. http.timeout(seconds)bounds connecting and each read, and is checked between reads, rather than being one hard deadline for the whole transfer.RADLANG_TLS_CA(a PEM or DER file to trust instead of the system’s certificates) works;RADLANG_TLS_INSECUREis not supported (TLS stays verified).- Compressed responses are decompressed, and their
Content-Encodingheader is removed. The defaultUser-Agentis the platform’s (Dalvik/2.1.0 …), and aDELETEwithout a body carriesContent-Type: application/x-www-form-urlencoded. - The app gets the
INTERNETpermission automatically when it uses the client.
Requests may be made from any thread, async tasks included.
On iOS
iOS ships no libcurl an app may load, so on --target ios / ios-simulator
the client runs over NSURLSession, behind the same curl interface as Android:
the API, response fields and headers, redirects, the streaming client,
retry, circuitBreaker and proxy behave as above, and failures carry
libcurl’s codes and messages (6, 7, 28, 60 for a rejected certificate,
…). TLS uses the system trust store, and the system proxy applies unless
http.proxy sets one. Differences:
- Cleartext
http://to a host name is blocked by App Transport Security and fails with code1and a message saying so (IP addresses andlocalhostare allowed); usehttps://, or add anNSAppTransportSecurityexception to the app’s Info.plist. - Streamed
text/plainbodies may arrive in larger chunks: NSURLSession holds back the first 512 bytes of plain-text responses for content sniffing.text/event-stream(SSE) and binary types stream chunk by chunk. http.timeout(seconds)is the whole-transfer limit; the idle limit between packets is the same value.RADLANG_TLS_CA(trust only that CA) andRADLANG_TLS_INSECUREwork.- Compressed responses are decompressed and their
Content-EncodingandContent-Lengthheaders removed;Set-Cookieheaders are rebuilt from the parsed cookies (one per cookie); the defaultUser-Agentis the platform’s.
Requests may be made from any thread, async tasks included.
For MCP tool servers built on this HTTP layer, see MCP stdlib.
The HTTP server (httpserver)
Creating and starting
httpserver.serve(port: int, bindAddress?: string) : HttpServer
server.listen() : void // start; blocks the current thread
server.start() : void // start on a background thread; returns immediately
server.close() : void // stop the serverhttpserver.serve(8080, "127.0.0.1") binds only IPv4 loopback. The optional
address must be a numeric IPv4 address; hostnames and IPv6 are not supported.
Omitting it preserves the existing "0.0.0.0" default (all IPv4 interfaces).
The selected address is validated and bound inside serve, before the socket
starts listening; no initial wildcard listener is created. Invalid addresses,
ports outside 0–65535, and socket/bind/listen failures throw a catchable Error.
Port 0 requests an OS-assigned port.
Register routes on the server, then start it. Use listen() for a normal
foreground server, or start() when you need the program to keep running (for
example, to make client requests against your own server in a test).
listen() automatically scales across every CPU core — see
Multi-core scaling. start() stays single-process.
An HttpServer lives until close(), independent of the function that created
it: an async fn can serve, register routes and start() it, store it in a
namespace variable and return; the routes keep working (their handlers’
captured values stay alive with the server) and another function can close()
it later.
HTTPS (TLS)
Serve HTTPS natively — no reverse proxy required — by attaching a certificate and private key before starting the server:
server.tls(certPath: string, keyPath: string) : voidfn main() {
HttpServer server = httpserver.serve(8443)
server.tls("certs/cert.pem", "certs/key.pem") // enable HTTPS
server.get("/", fn(HttpRequest req): HttpResponse {
return HttpResponse(200, "hello over TLS")
})
server.listen()
}certPath and keyPath are PEM file paths loaded at runtime, so private
keys stay out of the compiled binary (same posture as .radenv). The
certificate file holds the leaf certificate first, followed by any intermediate
chain certificates; the key may be RSA or EC (prime256v1). Paths resolve
relative to the project root. If either file is missing or malformed the server
refuses to start rather than silently falling back to plaintext.
TLS is powered by a vendored, statically-linked BearSSL
engine (no OpenSSL dependency), which negotiates TLS 1.2 with modern
forward-secret ECDHE cipher suites. Everything downstream — routing, middleware,
static assets, server.ssr — is served encrypted with no code change.
Generate a self-signed certificate for local development with:
openssl req -x509 -newkey rsa:2048 -nodes -keyout key.pem -out cert.pem \
-days 365 -subj "/CN=localhost"Calling a TLS server from the http client. For a real certificate signed
by a public CA, no configuration is needed. To reach an internal service or a
self-signed dev server, point the client at the certificate to trust, or (dev
only) disable verification, via the environment:
RADLANG_TLS_CA=/path/to/ca.pem # pin a CA bundle / self-signed cert to trust
RADLANG_TLS_INSECURE=1 # disable peer/host verification (dev only)RADLANG_TLS_INSECURE logs a one-time warning so it can’t silently weaken a
production build.
The CA file can also be baked into the executable: runtime.tlsCA in
config.yaml (runtime: mapping) sets the same trusted CA bundle as
RADLANG_TLS_CA, and the environment variable overrides the baked value. It
applies to outbound TLS from the http client and, when startTls is given no
caPath, to tcp connections upgraded with it (see net).
Not yet over TLS:
server.ws(WebSocket upgrades) still takes over the raw socket and is skipped on a TLS listener —wss://is a follow-up.server.sseandserver.streamdo work over TLS: their writes go through the connection’s TLS state. The manualserver.accept()/server.respond()loop is also plaintext-only; uselisten()/start()for HTTPS.
Compression (gzip)
Responses are gzip-encoded automatically — there is nothing to enable. When a
request advertises Accept-Encoding: gzip, the server compresses the response
body and adds Content-Encoding: gzip and Vary: Accept-Encoding, provided:
- the content type is text-ish (
text/*,application/json,application/javascript,application/xml,image/svg+xml, and friends), and - the body is at least ~860 bytes (below that gzip rarely pays for its overhead).
Already-compressed types (images, video, fonts, archives) and small bodies are
sent as-is. Both dynamic handler responses and static assets served from
server.useStatic are covered; static files above 8 MB stream uncompressed to
keep memory bounded.
On the client side the http namespace advertises the encodings libcurl was
built with and transparently inflates gzip/deflate responses, so
http.getSync(url).body is always the decoded text — no manual step. Setting an
explicit Accept-Encoding header yourself opts out of that auto-decode and hands
you the raw encoded body.
Compression is powered by a vendored, statically-linked
miniz (no zlib dependency). The same codec
is exposed as the reusable compress namespace — gzip/deflate
(de)compression over strings or bytes, gzip metadata, and ZIP archive
create/extract — for use outside HTTP.
Caching (ETag / conditional requests)
Every static asset served through server.useStatic carries HTTP caching
validators automatically — there is nothing to enable. Each 200 response gets:
ETag— a strong validator derived from the file’s modification time and size (e.g."6710a3c0-1f4"). It changes whenever the file changes.Last-Modified— the file’s modification time as an HTTP date.Cache-Control— the caching policy (see below).
When a client revalidates — sending back the ETag in If-None-Match or the
date in If-Modified-Since — and nothing has changed, the server replies
304 Not Modified with no body, skipping the transfer entirely. Browsers do
this on their own once they’ve cached a response, so a repeat visit re-validates
cheaply instead of re-downloading. If-None-Match takes precedence over
If-Modified-Since (RFC 7232), and If-None-Match: * matches any existing file.
Cache-Control policy. By default assets are sent public, max-age=3600
(cacheable for an hour), with one deliberate exception: HTML is always
no-cache so an SPA/SSR index shell is never served stale — it still carries an
ETag, so revalidation is a cheap 304 rather than a full download. Tune the
max-age with server.cache:
server.cache(maxAgeSeconds: int) : voidfn main() {
HttpServer server = httpserver.serve(8080)
server.useStatic("dist")
server.cache(86400) // cache non-HTML assets for a day
server.listen()
}server.cache(0) sets no-cache for everything (assets still revalidate via the
ETag) — a useful setting during development. The configured max-age applies to
cacheable assets only; HTML always revalidates regardless.
For dynamic responses, set the headers yourself — the request headers and
hash namespace give you everything needed to revalidate by hand:
server.get("/report", fn(HttpRequest req): HttpResponse {
string body = buildReport()
string etag = "\"" + hash.sha1(body) + "\""
if (req.header("If-None-Match") == etag) {
return HttpResponse(304, "").setHeader("ETag", etag)
}
return HttpResponse(200, body).setHeader("ETag", etag)
}) Routing
server.get(path, handler)
server.post(path, handler)
server.put(path, handler)
server.delete(path, handler)
server.patch(path, handler)A handler is a function fn(HttpRequest): HttpResponse. Construct the response
with HttpResponse(status, body) or HttpResponse(status, body, headers), where
headers is a Map<string,string> or string[]. The content type defaults to
text/plain; set a different one as a Content-Type header, or pass the content
type itself as a string: HttpResponse(200, html, "text/html"). res.contentType
reads it back.
For a binary body of known length, use the explicit binary constructor:
fn download(HttpRequest req): HttpResponse {
byte[] data = fs.readBytesSync("bundle.zip")
return HttpResponse.withBytes(200, data, {
"Content-Type": "application/zip",
"Content-Disposition": "attachment; filename=\"bundle.zip\""
})
}HttpResponse.withBytes(status, byte[], headers?) snapshots the bytes, including
embedded NULs, and sends the exact length with Content-Length. HTTP/1.1
connections can be reused after the complete body is sent. Framing headers are
computed by the server; conflicting application or middleware framing fields
are normalized. Keep the original byte[] if the application needs to inspect
binary data: the existing response body field remains a string view.
The ordinary HttpResponse(...) constructor keeps its existing text conversion
behavior, including when given a byte list. Unknown-length responses continue
to use HttpStream; its chunked/SSE behavior is unchanged.
To serve a file from an authenticated route without buffering the whole file:
fn download(HttpRequest req): HttpResponse {
// Resolve and validate the path using the application's access rules.
return HttpResponse.withFile(200, "downloads/archive.zip", [
"Content-Type: application/zip",
"Content-Disposition: attachment; filename=\"archive.zip\""
])
}HttpResponse.withFile(status, path, headers?) snapshots the path and headers.
After the handler and middleware finish, the server opens the regular file and
reads it on the async worker pool, using one 64 KiB buffer per active response.
Socket writes yield under backpressure. The open descriptor supplies the fixed
Content-Length; complete responses can reuse the connection. File responses
use identity encoding even if gzip is requested, so buffering stays bounded.
They do not add range handling, static caching, or application path validation.
Opening happens when the response is sent, so later path changes can affect
which file is opened. A missing file gives 404, access denial or a non-regular
file gives 403, and other open/stat errors give 500, each with a plain text body.
Those error responses replace the requested status and headers. A read failure,
truncation, disconnect or failed write after headers closes the connection;
the server never appends another response to an incomplete body. Appended bytes
beyond the original length are not sent. Status 204/304 sends no file body and
does not open the path. As with withBytes, server-owned framing fields override
conflicting application/middleware fields. The existing string body view
contains the saved path, not the file contents.
Non-TLS sends share a 30-second deadline, including time between file reads. An in-progress filesystem operation finishes on the worker before cleanup; it is not forcibly cancelled. Existing TLS write behavior is unchanged. File descriptors and buffers are released on success, failure and request teardown.
fn main() {
HttpServer server = httpserver.serve(8080)
server.get("/hello", fn(HttpRequest req): HttpResponse {
return HttpResponse(200, "hello world") // text/plain
})
server.get("/data", fn(HttpRequest req): HttpResponse {
return HttpResponse(200, "[]", { "Content-Type": "application/json" })
})
server.post("/echo", fn(HttpRequest req): HttpResponse {
return HttpResponse(200, req.body)
})
server.listen() // blocks, serving requests
} Async handlers
A route handler may also be an async fn(HttpRequest): HttpResponse, named
or inline.
Each request is served in its own coroutine, so a handler’s await points
suspend and resume transparently — you write straight-line code that awaits a
db read, an outbound http.get, or any other future, and return the response
normally:
async fn showUser(HttpRequest req): HttpResponse {
DbUsers[] rows = await conn.select().from(UsersTbl).where("id = 1")
return HttpResponse(200, rows[0].name, "text/plain")
}
fn main() {
HttpServer server = httpserver.serve(8080)
server.get("/user", showUser) // pass the async fn by name
server.listen()
}An inline async fn(...) literal works the same way and captures the variables
it uses, so a function, including a generic one, can register handlers that close
over its arguments:
fn page<T>(HttpServer server, string path, fn(HttpRequest): T loader) {
server.get(path, async fn(HttpRequest req): HttpResponse {
T props = loader(req)
HttpResponse r = await http.get("http://127.0.0.1:3000/render")
return HttpResponse(200, json.from(props) + r.body, "text/plain")
})
}Prefer an async handler with await over sys.blockOn(future) (or a ...Sync
call) inside a plain handler: a blocked handler holds its worker, while awaiting
handlers on one worker overlap.
Route groups
server.group(prefix) returns a RouteGroup. Routes, middleware and rate limits
registered through it are ordinary server registrations with the group’s prefix
prepended, so existing server.get(...) calls are unaffected and nothing about
matching changes.
server.group(prefix: string) : RouteGroup // prefix must start with "/"
group.group(prefix: string) : RouteGroup // nested: prefixes concatenate
group.get/post/put/delete/patch(path, handler)
group.ws/sse/stream(path, handler)
group.use([path,] handler) // middleware scoped to prefix/*
group.rateLimit([subPrefix,] requests, windowMs) // see Rate limitingRouteGroup api = server.group("/api/v1")
api.get("/users", listUsers) // GET /api/v1/users
api.get("/users/:id", showUser) // path parameters work as usual
api.post("/users", createUser)
RouteGroup admin = api.group("/admin") // /api/v1/admin/...
admin.use(requireAdmin) // runs only for /api/v1/admin/*
admin.get("/stats", stats)Joining rules: a trailing slash on a prefix is dropped ("/api/" is "/api"), a
route path without a leading slash gets one, and "" or "/" registers the
group’s own prefix (api.get("/", h) serves /api/v1). A request for
/api/v1/ with a trailing slash is not matched unless registered, exactly as for
plain routes. group.use(handler) is server.use("<prefix>/*", handler), so it
also runs for the bare prefix path and for unmatched (404) requests under it. Group methods are valid on a var, and a
group call can be chained (server.group("/x").get("/y", h)).
Controllers
A struct annotated [controller("/prefix")] can declare its routes as methods.
Mount an instance with server.addController(instance); each method with a verb
attribute ([get], [post], [put], [delete], [patch], optionally with a
sub-path such as [get("/:id")]) becomes a route under the prefix. Inside a
method me (and @field) is the handler’s own copy of the mounted instance, so
a change lasts for that request only.
type Todo { int id, string title, bool done }
type CreateTodoDto { string title, bool done }
fn requireBearer(string auth): void {
if (auth == "") { throw Error("missing Authorization header", 401) }
}
[controller("/api/todos")]
type TodoController {
string svc
[get]
fn all(): Todo[] { // 200 application/json
return [Todo(1, "buy milk", false)]
}
[get("/search")]
fn search([query] int page, [query("q")] string term): string {
return "page=" + page.toString() + " q=" + term // text/plain
}
[get("/:id")]
[useGuard(requireBearer)]
fn byId([param] int id, [header("X-Trace")] string trace): Todo {
if (id == 404) { throw Error("not found", 404) }
return Todo(id, "x", true)
}
[post]
fn create([body] CreateTodoDto dto): CreateTodoDto {
return CreateTodoDto(dto.title, !dto.done)
}
}
fn main() {
HttpServer server = httpserver.serve(8080)
server.addController(TodoController("todos"))
server.listen()
}- Parameter binding.
[param]reads a route segment (:id),[query]a query-string value ([query("q")]names the key; otherwise the parameter name is used),[header("Name")]a request header and[body]the JSON request body parsed into a DTO. Integer (int,uint,long,byte), floating-point,boolandstringparameters are converted from the text; a value that does not convert (for example/api/todos/xyzfor anintparameter) arrives as0, not as a400. - Return values. An
HttpResponseis sent as it is. Astringis sent astext/plain. Any other value (a struct, a list) is serialized withjson.fromand sent asapplication/json. - Bodies. A
[body]that is not valid JSON answers400with{"error":"Invalid request body"}before the method runs. DTO fields can carry[required],[email],[minLength(n)],[maxLength(n)]and[range(lo, hi)]; a failing body answers400application/problem+jsonwith anerrorsarray of{ "field", "message" }(an absent optional field is not checked). - Errors. A throw out of a method becomes an RFC 7807
application/problem+jsonresponse: theError’scodeis the HTTP status (clamped to a valid range,500for0) and itsmessageis thedetail. - Guards.
[useGuard(fn)]on a method runsfn(string authorization): voidwith theAuthorizationheader first; throwingError(msg, 401)orError(msg, 403)denies the request through the same error response.
A controller may live in a namespace, where its methods reach the namespace’s functions and nested namespaces unqualified. Controller routes are ordinary server routes, so middleware and the not-found handler apply to them.
The request object
HttpRequest carries the incoming request:
| Field | Type | Meaning |
|---|---|---|
method |
string | HTTP verb (GET, POST, …) |
path |
string | Request path |
query |
string | Raw query string |
body |
string | Request body |
headers |
string | Raw headers block |
req.bodyBytes() : byte[] returns the request body as bytes (embedded NUL bytes
included), where req.body is the text view. Three helper methods pull named values out:
req.param(name: string) : string // a captured route parameter (:name / *)
req.query(name: string) : string // a query-string parameter, URL-decoded
req.header(name: string) : string // a request header value (case-insensitive)
req.hasHeader(name: string) : bool // is the header present?
req.headerAll(name: string) : string[] // every value of a repeated header
req.headers() : string[] // every "Name: value" linereq.paramreads a segment captured by a route pattern, e.g.:idin/user/:idor*for a wildcard.req.queryreads a?key=valueparameter and URL-decodes it for you; absent keys return"".- Header lookups are case-insensitive (
req.header("x-test")matchesX-Test).req.headerreturns""for an absent header; usereq.hasHeaderto distinguish absent from empty.req.headerAllcollects every value of a repeated header (e.g.Set-Cookie).
// route: /user/:id requested as /user/42?tab=billing&q=hello%20world
server.get("/user/:id", fn(HttpRequest req): HttpResponse {
string id = req.param("id") // "42"
string tab = req.query("tab") // "billing"
string q = req.query("q") // "hello world" (decoded)
string auth = req.header("Authorization")
return HttpResponse(200, "user " + id, "text/plain")
}) File uploads (multipart/form-data)
multipart.parse(req) splits a multipart/form-data request body into its
parts. It reads the raw body binary-safely (by the exact byte count, so file
uploads with embedded NULs survive) and takes the boundary from the request’s
Content-Type header. It returns a FormPart[]:
| Field | Type | Meaning |
|---|---|---|
name |
string | The form field name |
filename |
string | The uploaded file’s name ("" for a plain field) |
contentType |
string | The part’s own Content-Type ("" if absent) |
data |
byte[] | The raw part body |
server.post("/upload", fn(HttpRequest req): HttpResponse {
FormPart[] parts = multipart.parse(req)
for (FormPart p in parts) {
if (p.filename != "") {
// A file part: persist the raw bytes to disk.
fs.writeBytesSync("uploads/" + p.filename, p.data)
} else {
// A plain text field: decode the bytes to a string.
string value = p.data.toString()
}
}
return HttpResponse(200, "ok")
})A part with an empty filename is an ordinary form field; a non-empty
filename marks a file upload. Use p.data.length() for the byte size and
p.data.toString() to read a text field’s value.
Redirects
An HttpResponse has a redirect helper that produces a 302 pointing at
another URL:
server.get("/old", fn(HttpRequest req): HttpResponse {
HttpResponse res = HttpResponse(200, "", "text/plain")
return res.redirect("/new")
}) Custom response headers
Set response headers with res.header (append) or res.setHeader (replace).
Both return the response so calls chain:
res.header(name: string, value: string) : HttpResponse // append (allows duplicates)
res.setHeader(name: string, value: string) : HttpResponse // replace any existing same-named headerserver.get("/data", fn(HttpRequest req): HttpResponse {
return HttpResponse(200, "[]", "application/json")
.header("X-Total-Count", "0")
.setHeader("Cache-Control", "no-store")
})Use header when you deliberately want repeated headers (e.g. multiple
Set-Cookie); use setHeader when a header should appear once. The same two
methods are available on the live res handle inside middleware. CR/LF
characters in a header name or value are stripped automatically, so a
user-supplied value can’t inject extra headers (HTTP response splitting).
Custom 404
server.notFound(handler)server.notFound(fn(HttpRequest req): HttpResponse {
return HttpResponse(404, "Nothing here", "text/plain")
}) Static assets
server.useStatic() // serve files from cfg.staticDir (default "public")
server.useStatic("dist") // serve from a different directory insteaduseStatic() serves files at the URL root: a GET/HEAD request for
/app.css returns <staticDir>/app.css, and / or any path ending in /
returns index.html from that directory. The Content-Type is inferred from
the file extension (html, css, js/mjs, json, svg, png, jpg, gif, webp, ico,
txt, xml, pdf, wasm, woff/woff2, ttf, mp4, webm, mp3 — anything else is served
as application/octet-stream).
fn handleUsers(HttpRequest req): HttpResponse {
return HttpResponse(200, "[]", "application/json")
}
fn main() {
HttpServer server = httpserver.serve(8080)
server.get("/api/users", handleUsers)
server.useStatic() // everything else tries public/ then notFound
server.listen()
}The lookup order is dynamic routes first, then a static file, then the 404
handler — a matching get/post/… route always wins over a file of the same
path, and a static miss falls through to notFound. Middleware registered with
use() does not run for static hits; they are streamed straight from disk.
Static assets are served with ETag, Last-Modified, and Cache-Control
validators, and revalidating clients get a 304 Not Modified — see
Caching. Tune the policy with
server.cache(seconds).
The directory comes from paths.static in config.yaml (default public) and
is resolved relative to the process’s working directory at run time. Request
paths are percent-decoded and any .. traversal is rejected. It is also
readable in code as cfg.staticDir.
# config.yaml
paths:
static: "public" Server-side data (server.ssr)
server.ssr hands server-computed data to a client framework in the first
byte of HTML, so the page hydrates without a client fetch round-trip. It is
framework-agnostic: the handler returns any JSON-serializable value and the
server injects it as a global, which React, Vue, Svelte, or vanilla JS all read
the same way.
server.ssr("/", fn(HttpRequest req): DashData {
return DashData(currentUser(req), recentStats()) // any struct/value
})The handler’s return value is the props — any JSON-serializable value (struct,
list, map, primitive). The HttpRequest parameter is optional: take it to
personalize the first paint (a route param, cookie, or query), or omit it when
every visitor gets the same data.
server.ssr("/stats", fn(): SiteStats { // no request needed
return SiteStats(userCount(), uptime())
})The returned value is JSON-serialized and spliced into a static HTML template as:
<script>window.__RAD_PROPS__=<your data as JSON></script>The client reads that global on boot instead of fetching:
const props = window.__RAD_PROPS__; // present in the first paint
hydrateRoot(document.getElementById("root"), <App {...props} />);A typed, framework-agnostic accessor for the client side ships in
ts/rad-ssr.interface.ts (getRadProps<T>() / requireRadProps<T>()).
Template. By default the template is <cfg.staticDir>/index.html. Pass an
explicit template as a string literal to override it:
server.ssr("/", "dist/index.html", fn(HttpRequest req): DashData { ... })The injection point is chosen in this order: the <!--rad-ssr--> marker if the
template contains one (replaced in place), else immediately before </head>,
else before </body>, else appended. Place the marker to control exactly where
the props land:
<head>
<title>Dashboard</title>
<!--rad-ssr-->
</head>One-call SPA + data. useStatic takes an optional trailing props handler,
folding “serve the bundle and inject props into the index shell” into a single
registration:
server.useStatic("dist", fn(HttpRequest req): DashData {
return DashData(currentUser(req), recentStats())
})This serves dist/ statically and injects props into index.html at /.
Non-index assets (/bundle.js, /app.css, …) stay on the pure static path and
are streamed untouched. useStatic(fn) uses cfg.staticDir as the directory.
When a handler is present the directory must be a string literal (the template
path is resolved at compile time).
Escaping. Prop values are HTML-escaped inside the script tag (<, >, &
become their \uXXXX forms, plus the U+2028/U+2029 line separators), so a value
containing </script> cannot break out of the tag.
Registration. An ssr route is a GET handler and follows the same
precedence as any dynamic route: it wins over a static file of the same path. If
the template file is missing at request time the server logs a warning and
serves a minimal props-only shell (status 200) so hydration data still reaches
the client.
What this is not. server.ssr injects data into the first paint; it does
not render your components to HTML on the server (no renderToString, no SEO
benefit from server-rendered markup). The page still hydrates from client JS.
True server-side rendering (a Node sidecar streaming rendered HTML) is a separate
future mode; the server.ssr(path, fn) surface is shaped so it can slot in
behind a config flag without changing this handler signature.
Cookies
Cookies are handled through two types:
Cookie— a single cookie with all standard fields. Build one withCookie(name, value)and set attributes with fluent, chainable setters.CookieJar— a collection of cookies. Read one off a request, or build a fresh one to attach to a response.
Cookie(name: string, value: string) : Cookie // constructor
// fluent setters (each returns the Cookie)
cookie.path(value: string) : Cookie
cookie.domain(value: string) : Cookie
cookie.maxAge(seconds: int) : Cookie
cookie.expires(value: string) : Cookie
cookie.httpOnly(value: bool) : Cookie
cookie.secure(value: bool) : Cookie
cookie.sameSite(value: string) : Cookie // "Strict" | "Lax" | "None"
// readable fields
cookie.name cookie.value cookie.path cookie.domain
cookie.maxAge cookie.expires cookie.httpOnly cookie.secure cookie.sameSiteCookieJar() : CookieJar // new empty jar
jar.get(name: string) : Cookie // empty Cookie (name "") if absent
jar.add(cookie: Cookie) : void // add / replace by name
jar.remove(name: string) : void // drop from the jarReading request cookies — req.cookies() parses the incoming Cookie:
header into a jar (name/value pairs only; requests carry no attributes):
server.get("/me", fn(HttpRequest req): HttpResponse {
Cookie session = req.cookies().get("session")
if (session.value == "") {
return HttpResponse(401, "no session", "text/plain")
}
return HttpResponse(200, "hi " + session.value, "text/plain")
})Setting response cookies — build a jar and attach it with
res.cookies(jar), which emits a Set-Cookie: header per cookie:
server.get("/login", fn(HttpRequest req): HttpResponse {
CookieJar jar = CookieJar()
jar.add(Cookie("session", "abc123")
.path("/")
.maxAge(3600)
.httpOnly(true)
.secure(true)
.sameSite("Lax"))
return HttpResponse(200, "ok", "text/plain").cookies(jar)
})Read-modify-write — res.cookies() (no argument) returns a fresh,
modifiable copy of the cookies already set on a response. Modify it and put it
back with res.cookies(jar); the setter replaces the response’s cookies, so a
get → modify → put round-trip is idempotent:
CookieJar jar = res.cookies()
jar.add(Cookie("theme", "dark"))
res = res.cookies(jar)To expire a cookie in the browser, set one with maxAge(0); jar.remove(name)
only drops it from the jar (it won’t be sent).
Sessions (session, stdlib)
The session stdlib namespace (import { session } from stdlib) provides
stateless, signed session cookies. A session is an HS256 JWT (interop-grade,
verifiable by the jwt namespace and any standard library) carried in an
httpOnly, SameSite=Lax cookie. Because the whole session lives in the signed
cookie there is no server-side store to synchronise: it survives restarts and
scales across processes. Tampering, a wrong secret, or a passed exp all make
the session invalid.
session.issue(secret, payloadJson, ttlSeconds) : string // a raw signed token
session.save(res, secret, payloadJson, ttlSeconds) : HttpResponse // res + session cookie
session.load(req, secret) : string // verified payload JSON, or ""
session.active(req, secret) : bool // valid, unexpired session present?
session.value(req, secret, key) : string // one payload field, or ""
session.clear(res) : HttpResponse // expire the cookie (log out)
session.cookieName() : string // the cookie name ("rad_session")Build the payload with json.from. save stamps an exp claim ttlSeconds
out and matches the cookie Max-Age, so the token and browser cookie expire
together. save/clear are fluent — return the response they hand back.
// Log in: sign a session and set the cookie.
server.post("/login", fn(HttpRequest req): HttpResponse {
// ... verify credentials ...
return session.save(HttpResponse(200, "ok"),
secret, json.from({ userId: "u1", role: "admin" }), 3600)
})
// Read the session on a protected route.
server.get("/me", fn(HttpRequest req): HttpResponse {
if (!session.active(req, secret)) {
return HttpResponse(401, "unauthorized")
}
string uid = session.value(req, secret, "userId")
return HttpResponse(200, "hi " + uid)
})
// Log out.
server.post("/logout", fn(HttpRequest req): HttpResponse {
return session.clear(HttpResponse(200, "bye"))
})issue returns the raw token for when the client carries the session itself
(e.g. an Authorization: Bearer header) rather than a cookie.
Signed cookie sessions (server.session)
For a small amount of per-browser state without a server-side store, the runtime
offers native signed-cookie sessions. They are separate from the stdlib session
(JWT) namespace above and can be used independently.
server.session(secret: string, ttlSeconds: int = 86400, secure: bool = false) : void
req.session() : Map // verified values; empty Map if none
res.session(values: Map) : HttpResponse // sets (replaces) the session cookie
res.clearSession() : HttpResponse // expires the cookie in the browserserver.session(cfg.env("SESSION_SECRET"), 3600)
server.post("/login", fn(HttpRequest req): HttpResponse {
// ... verify credentials ...
Map s = req.session()
s.set("user", "bob")
return HttpResponse(200, "ok").session(s)
})
server.get("/me", fn(HttpRequest req): HttpResponse {
Map s = req.session()
if (!s.has("user")) {
return HttpResponse(401, "sign in")
}
return HttpResponse(200, "hi " + s.get("user"))
})
server.post("/logout", fn(HttpRequest req): HttpResponse {
return HttpResponse(200, "bye").clearSession()
})The cookie is named rad_sess and is sent with Path=/; HttpOnly; SameSite=Lax; Max-Age=<ttl>, plus Secure when secure is true or the server has server.tls
configured (pass secure = true behind a TLS-terminating proxy). Values are
strings; keys and values may contain any characters except NUL. The finished cookie
is limited to 4000 bytes once sealed; res.session throws a catchable Error
(session: values are too large for a cookie (limit 4000 bytes once sealed)) rather than
truncate. secret must be at least 16 characters (an Error otherwise); load it
from the environment, not source.
How it works and what it protects. The cookie value is
base64url(payload) "." base64url(HMAC-SHA256(secret, tag + base64url(payload)))
where the payload holds an absolute expiry and the values. req.session() verifies
the signature with a constant-time comparison and checks the expiry; a missing,
malformed, truncated, tampered, expired or differently-signed cookie reads as an
empty Map, never an error. A repeated rad_sess cookie is accepted if any copy
verifies.
- Integrity and expiry are enforced; confidentiality is not. The payload is only encoded, so a user can read their own session. Do not put secrets in it.
- Sessions are stateless:
clearSessiononly asks the browser to drop the cookie, and a copy of a still-valid cookie keeps working until it expires. Use a short TTL or keep a revocation list in your own store for logout-sensitive data. Rotatingsecretinvalidates every session. SameSite=Laxblocks cross-site POSTs from carrying the cookie but is not a full CSRF defence for state-changing GET routes; validate a token for sensitive forms.- Configuration is process-wide and belongs to the most recently created server (the
request and response values carry no server reference). A multi-core
listen()runs each worker as its own process, so each worker configures it itself; use the samesecreteverywhere so a cookie is valid on any worker. res.sessionandres.clearSessionare for route handlers (immutableHttpResponse); middleware can callres.setCookiewith its own cookie instead.
Middleware
server.use(handler) // runs for every request
server.use(path, handler) // a bare path runs only for that exact path;
// "/api/*" runs for everything under /apiMiddleware is Express-style: a handler receives the request and/or a live
response handle plus a next callback, and returns void. It comes in three
overloaded shapes — pick whichever arguments you need:
| Signature | Use |
|---|---|
fn(HttpRequest, NextFn): void |
inspect the request |
fn(HttpResponse, NextFn): void |
mutate the response |
fn(HttpRequest, HttpResponse, NextFn): void |
both |
Call next() (no arguments) to run the rest of the chain — downstream
middleware and the matched route handler. Skip next() to short-circuit: the
current response is sent and no downstream handler runs. This is how you reject a
request (auth, rate-limiting) without letting it reach the route.
Middleware also runs before server.stream and server.sse routes: the stream
handler only starts if every middleware calls next(), and headers a passing
middleware sets are sent with a server.stream response. WebSocket upgrades
(server.ws) do not run middleware.
The res handle is live — its setters change the response in place, so they
persist regardless of whether you call them before or after next(). The 0-arg
getters read the response as it stands right now, so calling them after
next() returns the downstream handler’s response (wrap/append/logging):
| Method | Effect |
|---|---|
res.status(int) |
set the status code |
res.body(string) |
set the response body |
res.header(name, value) |
add a response header |
res.setCookie(Cookie) |
add a Set-Cookie header (full Cookie builder) |
res.status() |
read the current status code (int) |
res.body() |
read the current body (string) |
res.contentType() |
read the current content type (string) |
A helper that receives this live handle should declare HttpResponseHandle:
fn decorate(HttpResponseHandle res) { res.header("X-App", "demo") }.
An ordinary HttpResponse parameter is an immutable response value; return
its updated builder result and capture that result at the call site. These
types cannot be passed interchangeably, including inside namespaces.
Ordering follows the onion model: the first-registered middleware is outermost,
so its code after next() runs last (and wins on any field it overwrites). A
route handler stays the return-based fn(HttpRequest): HttpResponse.
// Wrap the downstream response by reading it back after next().
server.use("/api/*", fn(HttpResponse res, NextFn next): void {
next()
if (res.status() == 200) {
res.body("[" + res.body() + "]")
}
})fn main() {
HttpServer server = httpserver.serve(8080)
// (res, next): attach a session cookie + header, then continue.
server.use(fn(HttpResponse res, NextFn next): void {
res.setCookie(Cookie("sid", "abc").path("/").httpOnly(true))
res.header("X-Powered-By", "radlang")
next()
})
// (req, res, next) scoped to /api/*: reject unauthenticated requests by
// short-circuiting — no next(), so the route handler never runs.
server.use("/api/*", fn(HttpRequest req, HttpResponse res, NextFn next): void {
if (req.header("Authorization") == "") {
res.status(401)
res.body("unauthorized")
return
}
next()
})
server.get("/api/data", fn(HttpRequest req): HttpResponse {
return HttpResponse(200, "payload", "text/plain")
})
server.listen()
}Note:
reqis read-only in middleware — a middleware inspects the request but cannot rewrite it for downstream handlers.
Rate limiting (ratelimit)
ratelimit.check(key, limit, windowSeconds) is a fixed-window throttle. It
counts hits per key and returns 0 while the key is under limit within the
window (recording the hit); once at the limit it returns the whole seconds until
the window resets — send that as Retry-After. The counter store is
process-global and thread-safe, so it works across the server’s connection
coroutines.
ratelimit.check(key: string, limit: int, windowSeconds: int) : int // 0 = allowed, else Retry-After
ratelimit.reset(key: string) : void // forget a key's counterKey on req.ip() for a per-client limit, or a route name (or both) to scope it.
Install it as a server.use middleware to guard every route:
// 60 requests per minute per client IP.
server.use(fn(HttpRequest req, HttpResponse res, NextFn next): void {
int retry = ratelimit.check(req.ip(), 60, 60)
if (retry > 0) {
res.status(429)
res.header("Retry-After", retry.toString())
res.body("Too Many Requests")
} else {
next()
}
})reset(key) forgets a counter — for example, clear an IP’s login throttle after
a successful sign-in.
Server-wide rate limiting (server.rateLimit)
server.rateLimit enforces a per-client request budget natively, before routing and
middleware run, so it covers every route (including static files, server.sse and
server.stream) without any handler code. It is a token bucket: each client may
make requests requests per windowMs, spent as a burst and refilled continuously.
A request over budget gets 429 Too Many Requests with a Retry-After header (whole
seconds, at least 1) and a text/plain body, and never reaches a handler.
server.rateLimit(requests: int, windowMs: int) : void // default for every path
server.rateLimit(routePrefix: string, requests: int, windowMs: int) : void // override for a prefix
group.rateLimit([subPrefix,] requests, windowMs) // same, relative to a group
server.trustProxy(addresses: string[]) : void // see Trusted proxies
req.clientIp() : string // the address the limiter usesserver.rateLimit(100, 60000) // 100 requests per client per minute
server.rateLimit("/login", 5, 60000) // stricter budget for the login routes
server.rateLimit("/api", 10, 1000) // 10 requests per second under /api- A route override replaces the default for paths it covers, with its own separate
budget. A prefix covers a path on a segment boundary:
"/login"covers/loginand/login/resetbut not/loginx; the longest matching prefix wins. With only route overrides configured, other paths are unlimited. CallingrateLimitagain for the same scope replaces that limit and resets its counters. - The health (
server.healthCheck) and metrics (server.metrics) endpoints are never limited, so probes keep working. - A throttled request without a body keeps its connection open; one with a body is answered and the connection is closed, because the unread body cannot be skipped.
- Memory is bounded. Each limit tracks at most 65,536 clients; a client whose bucket
has fully refilled is indistinguishable from an unknown one and is dropped by an
incremental sweep on every check, and if the table is still full the oldest entry is
evicted. At most 16 limits can be configured.
requestsis 1 to 1,000,000,windowMs1 to 86,400,000; anything else, or configuring after the server started, throws anError. - Counters live in the process. With the multi-core
listen()each worker process keeps its own, so a client’s effective ceiling can approachrequeststimes the worker count; useRAD_HTTP_WORKERS=1, or enforce the limit in a shared external store, when an exact global limit matters. - The key is the client address, never a header a caller controls (see below).
Trusted proxies. Behind a reverse proxy every connection comes from the proxy’s
address, so the limiter would treat all users as one client. server.trustProxy lists
the proxies (IPv4/IPv6 addresses or CIDR ranges such as "10.0.0.0/8", "::1") whose
X-Forwarded-For header may be believed:
server.trustProxy(["127.0.0.1", "10.0.0.0/8"])
server.rateLimit(60, 60000)The socket peer is the client unless it matches the list. When it does, the header is
walked from the right (the hop the trusted proxy appended) and the first address that
is not itself trusted is the client, so entries a caller put to the left are ignored;
if every hop is trusted the leftmost is used. A malformed address anywhere in the
chain, more than 64 hops or more than 4 KiB of header falls back to the peer, and
IPv4-mapped IPv6 addresses match their IPv4 form. A malformed trustProxy entry throws.
Without trustProxy, X-Forwarded-For is never consulted, which is what stops a client
from dodging its limit by varying the header. req.clientIp() returns the same address
(req.ip() is always the raw socket peer); like server.session, the trusted list for
clientIp() is process-wide and belongs to the newest server.
Observability
Production servers expose request tracing, structured logs, and Prometheus metrics. Each is opt-in and independent.
server.jsonLogs() : void // structured JSON access logs
server.metrics(path: string = "/metrics") : void // Prometheus endpoint
server.healthCheck(path: string = "/health") : void
req.requestId() : string // per-request correlation ID Request IDs
Every request is stamped with a correlation ID. If the client sends an
X-Request-Id header it is honoured; otherwise the server generates one. The ID
is readable in handlers via req.requestId() and echoed back on the response as
X-Request-Id, so a trace can be followed across a call chain.
server.get("/order", fn(HttpRequest req): HttpResponse {
string rid = req.requestId()
// include rid in downstream calls / logs
return HttpResponse(200, "traced " + rid)
}) Structured logs
server.jsonLogs() turns the access log on and writes one JSON object per
request to stderr (method, path, status, latency, request ID, client IP), suited
to log aggregation. Without it the access log is off unless RADLANG_HTTP_LOG
is set, and then writes a plaintext line per request. Before 1.40.29
jsonLogs() only chose the format, so it logged nothing on its own.
Prometheus metrics
server.metrics() serves a Prometheus exposition endpoint (default /metrics).
It is a built-in route intercept that bypasses the middleware chain. Exposed
series include http_requests_total, http_requests_by_status,
http_requests_in_flight, a http_request_duration_seconds histogram, and
process_resident_memory_bytes.
server.metrics() // /metrics
server.metrics("/_stats") // custom path Health checks
server.healthCheck() serves a liveness endpoint (default /health) that
returns 200 ok while the server is running and 503 shutting down once a
graceful shutdown has begun — so a load balancer stops routing to a draining
instance.
Live dashboard: server.useSyn()
server.useSyn() starts the server and opens a native dashboard window for it
(macOS; elsewhere the server runs headless). Like listen() it is the last
call in main: it blocks until the window is closed, and closing the window
stops the program.
server.useSyn()
// or add the program's own UI as an extra tab
server.useSyn(fn(SynNode app) {
app.label("Queue").font({size: 18, weight: "bold"})
SynNode depth = app.label("0")
syn.every(1000, fn() { depth.setText(queue.length().toString()) })
})The window shows request totals, status classes, average latency, error rate and in-flight requests on every tab, plus:
| Tab | Contents |
|---|---|
| Traffic | every endpoint (searchable; click one to fill in :params, headers and a body, then Send a real request through the full middleware path — it runs in the background and reports status, time, response headers and the pretty-printed body) and the live request feed (filter by status class or text, pause, clear; click a line for the full request/response) |
| Latency | p50/p95, requests per second and p95 over the last minute, the latency histogram |
| System | memory, CPU, cores in use, threads, load average, total RAM; CPU and memory history |
| App | the program’s own syn UI, when a builder function is passed |
The App tab is ordinary syn code; timers (syn.every) and async
handlers work there as in any syn window.
Graceful shutdown
On SIGTERM the server stops accepting new connections and lets in-flight
requests finish within a drain window before exiting, so a rolling restart is
lossless. Keep-alive connections that are only waiting for their next request
are closed at once (clients reconnect), so they never hold the shutdown; the
process exits as soon as the last request in flight has been answered. Bound the
window with:
server.drainTimeout(seconds: int) : void // default 10 s (runtime.httpDrainMs)During draining the health-check endpoint reports 503, responses carry
Connection: close, and a stalled connection is additionally bounded by its
own request timeout.
Applications that intentionally accept large uploads can raise the per-server request body ceiling (8 MB by default):
server.maxBody(bytes: long) : voidRequests whose Content-Length exceeds the configured ceiling receive
413 Payload Too Large before their body is allocated.
Request bodies are framed by Content-Length only (RFC 7230 3.3.3). A request
that carries a Transfer-Encoding header (a chunked upload, say) is answered
501 Not Implemented, and Content-Length values that disagree (two header
lines, or one comma-separated list) are answered 400 Bad Request; either way
the connection is then closed, so bytes after such a request are never read as
another request. Behind a proxy, let the proxy buffer uploads and forward them
with a Content-Length (nginx does by default).
CORS
server.enableCORS()
server.allowCredentials()
server.allowOrigins(origins: string[])
server.allowHeaders(headers: string[])
server.allowMethods(methods: string[])Enable CORS and configure the allowed origins, headers, and methods. Preflight
OPTIONS requests are handled automatically once enabled.
fn main() {
HttpServer server = httpserver.serve(8080)
server.enableCORS()
server.allowOrigins(["https://example.com"])
server.allowMethods(["GET", "POST", "OPTIONS"])
server.allowHeaders(["Content-Type", "Authorization"])
server.get("/data", fn(HttpRequest req): HttpResponse {
return HttpResponse(200, "ok") // text/plain is the default
})
server.listen()
}WebSockets and Server-Sent Events
The same server also serves WebSocket and SSE endpoints alongside your normal routes, so one process can handle pages, a REST API, a WebSocket, and an event stream together.
server.ws(path, handler) // handler: fn(WebSocket): void (Socket is an alias)
server.sse(path, handler) // handler: fn(HttpRequest, SseStream): voidA ws route upgrades a matching Upgrade: websocket request (radlang does the
RFC 6455 handshake) and hands your handler a live WebSocket. An sse route
sends the text/event-stream headers and hands your handler a writable
SseStream. Both handlers run for the lifetime of the connection.
server.ws("/chat", fn(WebSocket ws): void {
while (ws.isOpen()) {
string msg = ws.receive()
if (msg != "") {
ws.send("echo: " + msg)
}
}
})
server.sse("/events", fn(HttpRequest req, SseStream stream): void {
int i = 0
while (stream.isOpen() && i < 10) {
stream.send("tick " + i.toString())
sys.sleep(1000)
i++
}
})Instead of the manual receive loop, a WebSocket handler can attach event
callbacks and let ws.listen() pump the connection (the handler argument may be
spelled Socket, an alias for WebSocket). This is the leak-resistant path:
listen() reclaims each message’s memory after the "message" handler returns,
so a long-lived connection stays flat. See net.md for the full event API and
the handler memory contract.
server.ws("/chat", fn(Socket ws): void {
ws.on("connect", fn(): void { sys.output("connected") })
ws.on("message", fn(string msg): void { ws.send("echo: " + msg) })
ws.on("disconnect", fn(): void { sys.output("gone") })
ws.listen()
})For the full WebSocket / SSE API (including the websocket.connect and
sse.connect clients), plus raw TCP and the Channel long-polling
primitive, see net.md.
Chunked streaming responses
When you need to stream an arbitrary response body — a large download, a report
built progressively, tokens from a model — server.stream opens an HTTP/1.1
chunked response you write to directly:
server.stream(path, handler) // handler: fn(HttpRequest, HttpStream): voidUnlike SSE (which fixes the text/event-stream framing), a stream sends raw
bytes with a status, content type, and headers you choose. The response head
is flushed lazily on the first write, so configure it before then:
HttpStream:
s.setStatus(code: int) : HttpStream // before first write
s.setContentType(ct: string) : HttpStream // before first write
s.setHeader(name: string, v: string) : HttpStream // before first write
s.write(chunk: string) : HttpStream // sends one chunk (flushes head on first call)
s.writeBytes(chunk: byte[]) : HttpStream // binary-safe chunk (embedded NULs preserved)
s.isOpen() : bool // has the client hung up?
s.close() : void // send the terminating chunk + closeserver.stream("/report.csv", fn(HttpRequest req, HttpStream s): void {
s.setContentType("text/csv")
s.setHeader("Content-Disposition", "attachment; filename=report.csv")
s.write("id,name\n")
for (int i in [1..1000]) {
if (!s.isOpen()) {
// the client disconnected: stop producing
return
}
s.write(i.toString() + ",row-" + i.toString() + "\n")
}
s.close()
})A callback may capture the stream during the request when the compiler proves that every use is synchronous. This includes a local callback reused by a helper that only invokes it or forwards it to another proven synchronous helper. A callback stored globally, returned, passed to a task or passed to an unproven callee keeps the existing escape checks. Rebuild libraries to publish their optional callback-lifetime proof; old libraries remain conservative.
Streams work on plain and TLS listeners (server.tls): chunks are encrypted through
the connection’s TLS state. A stream route can also sit in a route group
(group.stream), and server middleware and rate limits apply before the handler
starts. The lifecycle is: the handler runs once the request passes middleware; the
head (status, content type, headers) is sent with the first write/writeBytes/
close; each write is one HTTP chunk sent immediately; close() sends the
terminating chunk, and returning from the handler closes the connection.
Stream routes close their connection when the handler finishes. Their responses
always send Connection: close, overriding any middleware or handler
keep-alive header, so HTTP clients reconnect before their next request.
The setters and write return the stream, so they chain. A client reads the
result like any other response — the transport de-chunks it, so res.body is the
full concatenation of every chunk. CR/LF is stripped from setHeader names and
values, so a stream header can’t inject extra response headers.
Long-polling
To hold a normal HTTP request open until data is available, park the handler on
a Channel (see net.md). Because the handler yields while parked, one server
thread can keep many long-poll requests open at once.
Channel updates = Channel()
server.get("/poll", fn(HttpRequest req): HttpResponse {
string msg = updates.receiveTimeout(30000)
if (msg == "") {
return HttpResponse(204, "", "text/plain") // nothing yet; client retries
}
return HttpResponse(200, msg, "text/plain")
})
server.post("/publish", fn(HttpRequest req): HttpResponse {
updates.send(req.body)
return HttpResponse(200, "ok", "text/plain")
})Running in production
The server is built to be pointed at real traffic. A few things to know before you deploy.
TLS
The listener can serve HTTPS itself (server.tls, TLS 1.2; see the native HTTPS
section above). Behind a reverse proxy (nginx, Caddy, or your cloud load balancer),
plain HTTP on localhost is typical; do not expose a plain-HTTP port to the internet.
Multi-core scaling and process lifecycle
server.listen() uses a supervisor and fresh spawn + exec workers on macOS
and Linux. They share one listening socket and otherwise have independent
memory and system-library state. There is no fork-without-exec path. The kernel
distributes connections across their shared accept queue.
Worker count precedence remains RAD_HTTP_WORKERS > project.cores > available
CPUs, capped at 256. A request exceeding available CPU capacity warns and falls
back to one process. RAD_HTTP_WORKERS=1 disables the supervisor. Failed CPU
detection also falls back conservatively. Build-host config warnings do not
freeze the build machine’s CPU count into a deployment binary.
Startup runs again in every worker. Namespace initializers and main up to
listen() execute in the supervisor and in every worker, including replacements.
Move migrations, seeding and one-time file writes into onPrimaryStart. Globals
changed by the primary hook are not copied to workers; publish shared data in
an external store. A worker’s next request may go to another process.
ns workerData {
Database connection
fn migrate() {
Database setup = db.connect(cfg.env("DB_URL"))
setup.querySync("CREATE TABLE IF NOT EXISTS events (id INTEGER PRIMARY KEY)")
setup.close()
}
fn initialize() {
connection = db.connect(cfg.env("DB_URL"))
}
}
fn main() {
HttpServer server = httpserver.serve(8080)
server.onPrimaryStart(workerData.migrate)
server.onWorkerStart(workerData.initialize)
// Register routes using workerData here.
server.listen()
}Order: ordinary startup in each process; primary hook once in the supervisor;
spawn workers; worker hook in each serving process; readiness report; accept.
A worker reruns ordinary startup before its worker hook. The primary hook never
runs there. For single-process listen() both hooks run in the current process,
primary first. .start() runs both hooks on its serving thread, primary first,
and remains single-process. Using .start() keeps other servers in that process
single-process as before. Existing GPU initialization also retains its
single-process policy; GPU handles remain bound to their creating thread.
Both hooks take one synchronous fn(): void callback. Parameters, async
callbacks and non-void results are rejected. Register before starting; last
registration wins. Hooks run on the serving/root allocation context, not in a
request. Existing opaque-resource escape rules still apply. A throwing primary
hook spawns nothing and accepts nothing. A failed/recursive primary or worker
hook cannot be bypassed by retrying listen() on the same server. A worker
failure before readiness stops the supervisor and all siblings with a nonzero
exit. Worker startup (including ordinary initializers) has a 30-second deadline.
httpserver.isWorker(): bool is true only in a spawned worker, including from
namespace initializers. httpserver.workerIndex(): int is its stable zero-based
slot; both supervisor and single-process execution return false / -1. A
replacement worker keeps its slot. Use these for log tags or guarded startup
outside a server lifecycle; prefer onPrimaryStart for ordinary one-time work.
Workers inherit only stdio, the matching listening socket, a supervisor-death
pipe and a private readiness/control socket. Parent DB/file handles do not
survive exec. Internal RAD_HTTP_WORKER_FD, RAD_HTTP_DEATH_FD,
RAD_HTTP_BOOTSTRAP_FD and RAD_HTTP_WORKER_INDEX are not configuration APIs:
incomplete/forged values fail closed before application startup. The kernel
control-peer identity and socket address/port are validated; workers adopt the
socket instead of binding and never spawn another worker set. Each worker must
reconstruct the same server port/address. Multiple listening servers in a
spawned worker are unsupported and fail rather than silently binding.
A worker killed by a signal or exiting nonzero after readiness is logged and
respawned with 100/200/400/800/1600 ms backoff for successive deaths within a
60-second window. More than five deaths of one slot within that window stops
the supervisor with a nonzero exit. A clean worker exit is not respawned. There
are no respawns after shutdown starts. Supervisor SIGTERM/SIGINT stop accepting,
forward SIGTERM to workers, drain within drainTimeout, kill stragglers and
reap every child. Single-process SIGINT retains its ordinary signal exit;
SIGTERM uses graceful draining.
The death pipe also terminates workers if the supervisor is killed, including
while worker initialization is blocked.
Rolling SIGHUP reload, shared worker memory and Windows worker spawning are out of scope. The process protocol keeps socket handoff separate from startup so a future Windows implementation can use CreateProcess/socket transfer.
Built-in request limits
These guard against slow or oversized clients and are always on:
| Limit | Value | Behavior |
|---|---|---|
| Request read timeout | 30 s | A client that stalls mid-request is dropped. The deadline covers reading the whole request (headers and body); set it with runtime.httpRequestTimeoutMs. |
| Keep-alive idle time | 5 s | An idle persistent connection waits this long for its next request, then is closed. Sent as Keep-Alive: timeout=N (whole seconds, rounded up); set it with runtime.httpKeepAliveMs. |
| Max request body | 8 MB | A larger Content-Length gets 413 Payload Too Large; configure with server.maxBody(bytes). |
| Request framing | Content-Length |
Transfer-Encoding gets 501, disagreeing lengths 400; the connection closes. |
| Max concurrent connections | 1024 | Connections past the cap are shed. |
One slow connection never blocks the others — each is served on its own coroutine.
The two timeouts are runtime settings baked in from config.yaml; neither has
an environment variable or a server method. Both are in milliseconds, default
as shown above, range 1 to 2147483647 (clamped):
runtime:
httpRequestTimeoutMs: 30000 # whole-request read deadline
httpKeepAliveMs: 5000 # idle keep-alive waitThe graceful-shutdown window is runtime.httpDrainMs (default 10000, 0 allowed)
or server.drainTimeout(seconds).
Access logging
Off by default. Set the RADLANG_HTTP_LOG environment variable (to any value
other than 0) to emit one line per request on stderr:
RADLANG_HTTP_LOG=1 ./myserver
# GET /user/42 200 3ms Memory report
To see whether a server’s memory is per-request or accumulating, set
RADLANG_MEM_REPORT=1. Each completed request (including stream and SSE
routes) logs the process’s runtime memory on stderr, measured before the
request’s arena is released:
RADLANG_MEM_REPORT=1 ./myserver
# [mem] POST /v1/chat: managed 134.0 MB (329911 live), arenas 1280.0 MB committed
# (this request 207.0 MB), spilled/async 1221.5 MB in 1 regions- managed: managed-heap bytes handed out (live values, and freed small values waiting for reuse); growth across identical requests is a leak.
- this request: the request coroutine’s arena use, released when it ends.
Past the coroutine arena reservation (
RADLANG_CORO_ARENA_MB, 256 by default) allocations continue in 1 MB overflow chunks, counted under spilled/async together with async results and file mappings.
Add RADLANG_GC_TRACE=1 to follow each report with the functions that have
allocated the most managed-heap bytes.
Graceful shutdown
On SIGTERM (what systemd, Kubernetes, and docker stop send), the
server stops accepting new connections, closes idle keep-alive connections, lets
in-flight requests finish (up to a 10 s grace window), then exits cleanly — so a
rolling restart doesn’t drop responses mid-flight. An idle server exits
immediately, also when clients hold keep-alive connections to it. SIGINT (Ctrl-C) is
left as an immediate hard-kill for development.
When scaled across cores (the default), the supervisor forwards the shutdown to
every worker, waits out the grace window, and force-kills any straggler before
exiting. No worker ever outlives the main process — if the supervisor itself
is killed by any means, including an uncatchable SIGKILL, the workers detect it
and exit on their own. Killing the process you started always tears the whole
tree down.
Handler errors
An exception a handler does not catch fails only that request: a route handler
(or a middleware) answers 500 Internal Server Error — an enclosing
middleware’s next() returns normally — while a WebSocket, SSE or stream
handler, whose response has already started, ends there and the connection
closes (a chunked stream without its final chunk, so clients see it
incomplete). The message is logged to stderr
(radlang: handler for GET /path failed: ...) and the server keeps serving.
Startup failures
If the port can’t be bound (already in use, or a privileged port without
permission), the process prints the reason and exits non-zero. Run it under a
supervisor (systemd, a container orchestrator) that restarts it.
A full example
fn main() {
HttpServer server = httpserver.serve(8080)
server.use(fn(HttpResponse res, NextFn next): void {
res.header("X-Powered-By", "radlang")
next()
})
server.get("/", fn(HttpRequest req): HttpResponse {
return HttpResponse(200, "welcome")
})
server.notFound(fn(HttpRequest req): HttpResponse {
return HttpResponse(404, "not found")
})
// Start in the background so we can hit it from the same program.
server.start()
sys.sleep(150)
HttpResponse r = http.getSync("http://localhost:8080/")
sys.output(r.body) // welcome
server.close()
}Quick reference
Client (http)
| Call | Returns | Purpose |
|---|---|---|
http.get(url) / http.delete(url) |
Future<HttpResponse> |
Bodyless request (twins getSync/deleteSync) |
http.post/put/patch(url, body, headers?) |
Future<HttpResponse> |
Request with a body (twins postSync/…) |
http.request(method, url, headers, body) |
Future<HttpResponse> |
Full control incl. headers (twin requestSync) |
http.encode(s) / http.decode(s) |
string | URL percent-encode / decode (pure, sync) |
http.timeout(seconds) |
void | Set the client connect + transfer timeout (default 30s) |
A transport failure (refused/DNS/timeout/TLS) raises a catchable Error on
the …Sync path; the async path resolves with status == 0 and the message in
body. See Timeouts and transport errors.
Server (httpserver)
| Call | Purpose |
|---|---|
httpserver.serve(port) |
Create a server (HttpServer) |
server.get/post/put/delete/patch(path, handler) |
Register a route (handler is fn(HttpRequest): HttpResponse, sync or async, named or inline) |
server.ws(path, handler) |
Register a WebSocket route (see net.md) |
server.sse(path, handler) |
Register a Server-Sent Events route (see net.md) |
server.stream(path, handler) |
Register a chunked-streaming route (handler is fn(HttpRequest, HttpStream)) |
server.useStatic([dir]) |
Serve static files from dir (default cfg.staticDir) |
server.ssr(path, [template], handler) |
Inject handler’s value into a template’s first paint (handler is fn(HttpRequest): T) |
server.useStatic(dir, handler) |
Serve dir and inject props into its index shell at / |
server.cache(maxAgeSeconds) |
Set the static-asset Cache-Control max-age (0 = always revalidate) |
server.maxBody(bytes) |
Set this server’s maximum request body size (8 MB by default) |
server.addController(instance) |
Mount a [controller] struct’s verb-attributed methods as routes |
server.drainTimeout(seconds) |
Graceful-shutdown window (default 10 s) |
server.jsonLogs() / server.metrics([path]) / server.healthCheck([path]) |
JSON access log / Prometheus endpoint / liveness endpoint |
server.use([prefix,] handler) |
Register middleware |
server.notFound(handler) |
Custom 404 handler |
server.group(prefix) |
Create a RouteGroup whose routes/middleware/limits share a path prefix |
server.rateLimit([prefix,] requests, windowMs) |
Per-client token-bucket limit answered with 429 + Retry-After |
server.trustProxy(addresses) / req.clientIp() |
Trust X-Forwarded-For from listed proxies; read the resolved client address |
server.session(secret, [ttlSeconds], [secure]) |
Enable HMAC-signed cookie sessions (req.session(), res.session(map), res.clearSession()) |
server.tls(certPath, keyPath) |
Enable HTTPS from a runtime-loaded PEM cert + key (BearSSL, TLS 1.2) |
server.onPrimaryStart(fn(): void) |
Run one-time setup before spawning or serving |
httpserver.isWorker() / httpserver.workerIndex() |
Identify a spawned worker and its stable slot |
server.onWorkerStart(fn(): void) |
Initialize worker resources before accepting requests |
server.listen() / start() / close() |
Run (blocking) / run (background) / stop |
server.enableCORS() + allowOrigins/Headers/Methods(list) |
Configure CORS |
server.allowCredentials() |
Allow credentialed cross-origin requests; configured origins are reflected exactly |
req.param(name) / req.query(name) / req.header(name) |
Read a route param / query param / header |
res.header(name, value) |
Add a custom response header (chainable) |
res.redirect(url) |
Build a 302 redirect response |
Environment variables
| Variable | Effect |
|---|---|
RAD_HTTP_WORKERS |
Prefork worker count; it takes precedence over project.cores, which takes precedence over the CPU count (cap 256). 1 = single process. |
RADLANG_HTTP_LOG |
Any value but 0 enables one-line-per-request access logging. |
RADLANG_MEM_REPORT |
Any value but 0 logs runtime memory after each request (see Memory report) and prints the full report at exit (see Runtime memory). |
RADLANG_GC_TRACE |
Any value but 0 adds the top managed-heap allocating functions to each memory report. |
RADLANG_CORO_ARENA_MB |
No effect since 1.39: request coroutines allocate from the traced heap (see Runtime memory). |
RADLANG_CORO_STACK_KB |
Stack reservation per coroutine (default 8192, with a guard page; overflow is reported as a stack overflow). |
RADLANG_TLS_CA |
CA bundle file the http client trusts for outbound TLS (overrides runtime.tlsCA). |
RADLANG_TLS_INSECURE |
Any value but 0 disables TLS peer verification (development only). |
Runtime settings (config.yaml, runtime: mapping)
These bake a default into the executable (see runtime settings). None of the three timeouts has an environment variable.
| Key | Default | Effect |
|---|---|---|
runtime.httpTimeoutS |
30 (seconds, 1 to 2147483647) |
Client connect + transfer timeout; http.timeout(n) overrides it at run time. |
runtime.httpRequestTimeoutMs |
30000 (ms, 1 to 2147483647) |
Server read deadline for one whole request (headers and body). |
runtime.httpKeepAliveMs |
5000 (ms, 1 to 2147483647) |
How long an idle keep-alive connection waits for the next request; sent as Keep-Alive: timeout=N. |
runtime.httpDrainMs |
10000 (ms, 0 to 2147483647) |
Graceful-shutdown window; server.drainTimeout(seconds) overrides it. |
runtime.tlsCA |
none | Path of a CA bundle to trust for outbound TLS (the http client and tcp startTls); RADLANG_TLS_CA overrides it. |
Picking the right tool
- Calling an external API →
http.get/post/… , orhttp.requestwhen you need custom headers. - Building a service →
httpserver.serve+ route handlers. - Cross-cutting logic (auth, logging) →
server.usemiddleware withnext. - Browser clients →
server.enableCORS()and theallow*configuration. - Real-time push →
server.ws(bidirectional) orserver.sse(server → client); hold a plain request open with aChannelfor long-polling. Seenet.md.
Opt-in redirects and streaming clients
Existing client calls continue to expose redirect responses without following them.
http.requestFollowSync(method, url, headers, body, maxRedirects) follows up to
maxRedirects hops (0 disables following, range 0–100), returning the final
HttpResponse. Relative Location values are resolved against the current URL.
301/302 convert POST to GET; 303 converts methods other than HEAD to GET;
307/308 preserve method and body. Only HTTP(S) redirect targets are accepted;
redirect URLs containing credentials are rejected. All caller-supplied headers
are dropped permanently when an origin changes (scheme, host, or port), including
custom API-key headers. Final response headers replace intermediate headers.
http.streamSync(method, url, headers, body, onChunk, maxRedirects) uses the same
redirect policy and invokes onChunk: fn(byte[]) bool synchronously on the
calling thread as bytes arrive. Chunks are arbitrary decompressed byte sequences:
they are not UTF-8, line, SSE-event, or network-packet boundaries. Callers must
buffer and frame text themselves. Return false to stop immediately: no more
callbacks occur and the returned response has status 499 and an empty body.
Otherwise the final HTTP status and headers are returned, with an empty body.
Non-2xx responses also deliver chunks. Callback exceptions release native request
resources before propagating. Streams are not retried and use the configured HTTP
timeout and proxy; they do not use the legacy client’s circuit breaker.
Chunks are managed copies and may be retained after the callback. The HTTP client does not accumulate a response body, but normal managed-arena retention still applies; this is not a bounded-memory bulk-download API. Avoid retaining chunks when consuming SSE incrementally. These APIs block the calling thread; they do not return a Future.
Asynchronous streaming (http.stream)
http.stream(method, url, headers, body, onChunk, maxRedirects?) is the
non-blocking form: it returns a Future<HttpResponse> at once, runs the
transfer on a worker thread, and calls onChunk: fn(byte[]) bool on the
calling scheduler thread as bytes arrive, between other tasks; in a syn app
that is the UI thread, so the callback may update nodes directly.
maxRedirects defaults to 0 (redirects are returned, not followed).
async fn reply(string url, string[] headers, string body, SynNode label): void {
string text = ""
HttpResponse r = await http.stream("POST", url, headers, body, fn(byte[] chunk): bool {
text = text + chunk.toString() // frame SSE events yourself
label.setText(text)
return true
})
if r.status == 0 { sys.output("failed: " + r.body) }
}- Every chunk is delivered, in order, before the future resolves. The response has the final status and headers and an empty body.
- Returning false stops the transfer: no more callbacks, status 499.
- An exception thrown by
onChunkstops the transfer and rejects the future with that error. - A transport failure resolves with status 0 and the message as the body, like the other async verbs.
future.cancel()rejects the future at once (“future cancelled”) and no further callbacks run. On desktop the connection closes within about a second; on iOS and Android it closes at the next chunk or the HTTP timeout.- Chunks are allocated where the caller’s own values live, as with
streamSync; avoid retaining them in long streams.