cdt.http
Zero-dependency HTTP/1.1 client, server, and segment router (http.get, http.post, http.request, :param and *wildcard routes, keep-alive, in-memory dispatch for testing).
Import
import * as http from "cdt.http"Types
Request { method: String, path: String, body: String, headers: Map<String, String>, query: Map<String, String>, params: Map<String, String> }Response { status: Int, body: String, headers: Map<String, String> }BinaryResponse { status: Int, body: Bytes, headers: Map<String, String> }Cookie { name: String, value: String, path: String, domain: String, max_age: Int, http_only: Bool, secure: Bool, same_site: String }UploadedFile { name: String, filename: String, content_type: String, data: Bytes, size: Int }MultipartForm { fields: Map<String, String>, files: [UploadedFile] }HttpError { kind: String, message: String }RouterClient— Reusable HTTP/1.1 client with base URL, default headers, configurable timeout, and a thread-safe Keep-Alive TCP/TLS connection pool.
Module Functions
| Function | Signature | Description |
|---|---|---|
router | http.router() -> Router | Creates a new HTTP router. |
client | http.client(base_url?: String) -> Client | Creates a pooled keep-alive http.Client with an optional base_url (default timeout 30000 ms). |
build | http.build<T>() -> Router | Instantiates a Router from a declarative router Name { ... } schema. |
serve | http.serve<T>(addr: String) -> Void | HttpError | Builds and starts a blocking multi-threaded HTTP/1.1 server from a declarative router Name { ... } schema. |
text | http.text(body: String) -> Response | 200 OK with text/plain; charset=utf-8. |
html | http.html(body: String) -> Response | 200 OK with text/html; charset=utf-8. |
json | http.json(body: String) -> Response | 200 OK with application/json. |
ok_json | http.ok_json(val: T) -> Response | Encodes val as JSON and returns 200 OK (application/json). |
status_json | http.status_json(status: Int, val: T) -> Response | Encodes val as JSON with custom HTTP status. |
redirect | http.redirect(url: String, status?: Int) -> Response | Redirect response (302 by default) with location header. |
no_content | http.no_content() -> Response | 204 No Content empty response. |
response | http.response(status: Int, body: String) -> Response | Custom status code and body. |
response_with | http.response_with(status: Int, body: String, headers: Map<String, String>) -> Response | Custom status code, body, and headers. |
cookie | http.cookie(name: String, value: String) -> Cookie | Creates a Cookie builder (path="/", http_only=true, secure=false, same_site="Lax", max_age=-1). |
get | http.get(url: String) -> Response | HttpError | Sends an HTTP/HTTPS GET request (follows up to 10 redirects; http:// and https:// via built-in TCP/TLS client). |
post | http.post(url: String, body: String) -> Response | HttpError | Sends an HTTP POST request with body. |
get_json | http.get_json<T>(url: String, query?: Map<String, String>) -> T | HttpError | Sends GET (Accept: application/json), appends optional URL-encoded query, and decodes JSON into T. |
post_json | http.post_json(url: String, body: T) -> Response | HttpError | Encodes body as JSON and sends POST with Content-Type: application/json. |
request | http.request(method: String, url: String, body: String, headers: Map<String, String>) -> Response | HttpError | Sends a custom HTTP request with method, body, and headers. |
request_timeout | http.request_timeout(method: String, url: String, body: String, headers: Map<String, String>, timeout_ms: Int) -> Response | HttpError | Sends a custom HTTP request with an explicit timeout in milliseconds. |
get_bytes | http.get_bytes(url: String) -> BinaryResponse | HttpError | Sends an HTTP GET request and returns a BinaryResponse with a Bytes body. |
request_bytes | http.request_bytes(method: String, url: String, body: Bytes | [Int], headers: Map<String, String>) -> BinaryResponse | HttpError | Sends a binary HTTP request and returns BinaryResponse. |
The http.Request constructor accepts String or Bytes for its body argument. Incoming requests expose the raw payload in req.body_bytes and the original header value bytes in req.headers_bytes (with lowercase names for network requests). The text fields req.body and req.headers decode UTF-8 with replacement characters for invalid sequences. Routes with typed JSON bodies continue to require valid UTF-8.
BinaryResponse.body is a Bytes value. Use .to_list() when passing it to code that expects [Int].
Outbound Redirects
The HTTP client follows up to ten redirects and rejects redirects from HTTPS to HTTP. A change in scheme, host, or port removes all caller-supplied headers for the rest of the redirect chain, including default headers set on http.Client.
For 301, 302, and 303, the client sends non-HEAD requests as GET and removes the body along with Content-Length, Transfer-Encoding, Content-Type, Content-Encoding, and Expect. For 307 and 308, it sends the original method and body to the redirect destination.
Cookies (Cookie, Request, Response)
Incoming Cookie: headers are joined with "; " so multiple Cookie header lines are preserved. Responses store multiple Set-Cookie headers without overwriting one another and emit each as its own Set-Cookie: line on the wire:
c := http.cookie("sid", token)
.path("/")
.max_age(3600)
.http_only(true)
.secure(true)
.same_site("Lax")
resp := http.text("ok").set_cookie(c)?
resp = resp.clear_cookie("legacy", "/")?| Helper | Signature | Description |
|---|---|---|
Cookie builders | .path(s), .domain(s), .max_age(secs), .http_only(b), .secure(b), .same_site(s) | Fluent immutable Cookie builders (max_age < 0 omits Max-Age for session cookies; "None" requires secure(true)). |
resp.set_cookie | resp.set_cookie(cookie: Cookie) -> Response | HttpError | Validates name, value, path, domain, and same_site ("invalid_cookie") and appends a Set-Cookie line. |
resp.clear_cookie | resp.clear_cookie(name: String, path?: String) -> Response | HttpError | Appends an expired Max-Age=0; Expires=Thu, 01 Jan 1970 00:00:00 GMT Set-Cookie header (default path = "/"). |
resp.cookies / .cookie | resp.cookies() -> Map<String, String>, resp.cookie(name: String) -> String? | Parses Set-Cookie headers received by client or middleware responses. |
req.cookies / .cookie | req.cookies() -> Map<String, String>, req.cookie(name: String) -> String? | Parses incoming Cookie header pairs from Request. |
URL-Encoded Forms & Multipart Uploads
req.form() -> Map<String, String> | HttpError: parsesapplication/x-www-form-urlencodedbodies (%XXand+decoding, strict UTF-8, up to1024fields,"invalid_content_type"if anotherContent-Typeheader is set).req.form_all() -> Map<String, [String]> | HttpError: same validation and limits, preserving repeated keys as[String].req.multipart(max_bytes?: Int, max_parts?: Int) -> MultipartForm | HttpError: parsesmultipart/form-datacompletely in memory with zero implicit disk writes (defaults:10 MiBmax payload,64parts). Quoted boundaries are supported. Uploaded filenames inUploadedFile.filenamehave directory prefixes (/and\), quotes, and control bytes stripped (./..map to""). Access text fields viaform.fields, repeated fields viaform.fields_all(name) -> [String], and uploaded files viaform.files: [UploadedFile]. If you save uploads to disk, passfile.data(Bytes) explicitly tocdt.fsso runtime--allow-writesandbox permissions apply.
Client Methods (Keep-Alive Pool)
http.Client reuses idle HTTP/1.1 TCP and TLS connections per (host, port, tls) across requests, with up to 8 idle connections per host and a 60-second idle TTL.
When a fresh TCP connection is needed, HTTPS automatically attempts TLS 1.3 session resumption if the server previously sent a valid ticket. If the server declines the ticket, the client performs a full handshake. Requests are sent after the handshake completes.
If a pooled request fails while sending the request or parsing the response, the client can retry once on a fresh connection for GET, HEAD, OPTIONS, TRACE, PUT, and DELETE. For other methods such as POST and PATCH, the client returns the error. The server may already have processed the request by then.
| Method | Signature | Description |
|---|---|---|
header | c.header(name: String, value: String) -> Client | Returns a client copy (sharing the same pool) with default header name: value. |
bearer | c.bearer(token: String) -> Client | Sets Authorization: Bearer <token> on the client. |
timeout_ms | c.timeout_ms(ms: Int) -> Client | Sets request timeout in milliseconds. |
base_url | c.base_url(url: String) -> Client | Updates the client's base_url. |
deny_private_addrs | c.deny_private_addrs(enabled?: Bool) -> Client | Blocks loopback, private RFC 1918, CGNAT, link-local/metadata (169.254.169.254), and internal IPv6 addresses across URLs, DNS answers, and redirects ("blocked_addr"). Default true when called without arguments. |
get | c.get(path: String) -> Response | HttpError | Pooled GET against base_url + path (or full URL). |
delete | c.delete(path: String) -> Response | HttpError | Pooled DELETE request. |
post | c.post(path: String, body: String) -> Response | HttpError | Pooled POST request with string body. |
put | c.put(path: String, body: String) -> Response | HttpError | Pooled PUT request with string body. |
patch | c.patch(path: String, body: String) -> Response | HttpError | Pooled PATCH request with string body. |
get_json | c.get_json<T>(path: String, query?: Map<String, String>) -> T | HttpError | Pooled GET (Accept: application/json) decoding JSON into T. |
post_json | c.post_json(path: String, body: T) -> Response | HttpError | Pooled POST encoding body as JSON (Content-Type: application/json). |
request | c.request(method: String, path: String, body?: String, headers?: Map<String, String>) -> Response | HttpError | Pooled custom request with optional body and per-request headers. |
pool_stats | c.pool_stats() -> Map<String, Int> | Returns pool metrics ({"idle": <count>}). |
close | c.close() -> Void | Closes and drains all idle connections in the client's pool. |
api := http.client("https://api.example.com")
.bearer(token)
.timeout_ms(5000)
user := api.get_json<User>("/v1/me")?
api.close()Router Methods
| Method | Signature | Description |
|---|---|---|
get, post, put, delete, patch, options, head, any | r.<method>(pattern: String, handler: (Request) -> Response) -> Void | Registers a route (/users/:id, /files/*rest; any matches all methods). |
before | r.before(handler: (Request) -> Response?) -> Void | Registers a pre-handler hook; returning a Response short-circuits routing. |
after | r.after(handler: (Request, Response) -> Response) -> Void | Registers a post-handler hook to transform responses (e.g. CORS headers, logging). |
on_start | r.on_start(handler: () -> Void | Error) -> Void | Registers a startup hook executed before binding the listener in r.serve(...). |
on_stop | r.on_stop(handler: () -> Void | Error) -> Void | Registers a shutdown hook executed after draining in-flight requests and spawn tasks. |
dispatch | r.dispatch(req: Request) -> Response | Dispatches a Request in-memory (returns 404/405 automatically). |
serve | r.serve(addr: String) -> Void | HttpError | Starts a blocking HTTP/1.1 server on addr (e.g. "127.0.0.1:8080") with SIGINT/SIGTERM graceful shutdown. |
stop | r.stop() -> Void | Signals r.serve(...) to stop accepting new connections and shut down gracefully after in-flight requests finish. |
workers | r.workers(count: Int) -> Void | Configures the HTTP server worker thread count (1..=256). Overridden by CONDUIT_HTTP_WORKERS. |
timeouts | r.timeouts(idle_ms: Int, header_ms: Int, body_ms: Int) -> Void | Configures keep-alive idle (100..=300000 ms), header read (500..=300000 ms), and body read (500..=600000 ms) deadlines (non-positive keeps default). Overridden by CONDUIT_HTTP_*_TIMEOUT_MS. |
max_conns_per_ip | r.max_conns_per_ip(limit: Int) -> Void | Configures max concurrent connections per remote IPv4 address / IPv6 /64 prefix (0 disables per-IP limit). Overridden by CONDUIT_HTTP_MAX_CONNS_PER_IP. |
trusted_proxies | r.trusted_proxies(cidrs: [String]) -> Void | List of proxy IP/CIDR ranges (e.g. ["10.0.0.0/8", "172.16.0.0/12"]) exempt from per-IP connection limits. Overridden by CONDUIT_HTTP_TRUSTED_PROXIES. |
Server Configuration Precedence
On macOS and Linux (x86_64 / aarch64), serve runs an event-driven kqueue/epoll I/O reactor that keeps idle keep-alive sockets and slow/partial reads off the VM worker thread pool; other targets use a bounded blocking worker pool.
Server settings resolve with CONDUIT_HTTP_* environment variables > Router methods > built-in defaults:
CONDUIT_HTTP_WORKERS(1..=256; defaultclamp(cpus, 4, 16))CONDUIT_HTTP_IDLE_TIMEOUT_MS(100..=300000; default3000)CONDUIT_HTTP_HEADER_TIMEOUT_MS(500..=300000; default10000)CONDUIT_HTTP_BODY_TIMEOUT_MS(500..=600000; default30000)CONDUIT_HTTP_MAX_CONNS_PER_IP(defaultmax(workers / 2, 4);0disables)CONDUIT_HTTP_MAX_CONNS(16..=65536; reactor global concurrent connection cap, defaultclamp(workers * 128, 512, 8192))CONDUIT_HTTP_TRUSTED_PROXIES(comma-separated IPs/CIDRs; setting""overrides router-configured proxies to empty)
When per-IP limits, reactor capacity, worker queues, or the password-hashing concurrency gate are saturated, the server sheds excess requests with 503 Service Unavailable and Retry-After: 1.
Request Helper Methods
| Method | Signature | Description |
|---|---|---|
header | req.header(name: String) -> String? | Case-insensitive header lookup. |
param | req.param(name: String) -> String? | Route :param / *wildcard lookup. |
query_param | req.query_param(name: String) -> String? | Query-string parameter lookup. |
Declarative router DSL Features
Inside router Name { ... }:
group "/api/v1" { before auth; get "/users" => list_users }— Route prefix grouping with localbefore/aftermiddleware scoped to that prefix.guard auth_user { get "/me" => me }— Typed route guard block:auth_user(req: http.Request) -> Ctx | http.Responseshort-circuits onhttp.Responseor passesCtxas the last typed parameter to handlers inside the block.@http.querystruct binding — Annotate a struct with@http.queryto automatically parse and validate:parampath parameters and?key=valquery parameters (with defaults and@validation.*->400 invalid_query/422 validation_failed). Handlers can accept(http.Request, QueryStruct),(http.Request, QueryStruct, BodyStruct), and/orGuardCtx.@http.status(code)& typed return/error unions — Handlers can return any JSON-serializable typeT,Void(204),T?(200/404),http.Response, or a unionT | AppErrordirectly; annotateerrororstructtypes with@http.status(404)(unannotatederrordefaults to500,structdefaults to200). Both@http.queryparameters and typed return/error responses are reflected inconduit openapi.static "/assets" => "./public"— Serves static files withContent-Typedetection and path-traversal protection.cors "*"— Automatically handlesOPTIONSpreflight (204) and injectsaccess-control-allow-originon responses.on_start => init_fn/on_stop => cleanup_fn(oron start => .../on stop => ...) — Router-scoped lifecycle hooks (() -> Voidor() -> Void | Error).
Server Lifecycle Hooks & Graceful Shutdown
Conduit supports both top-level application hooks (on start { ... } / on stop { ... }) and router-level hooks (on_start => fn / on_stop => fn in router blocks, or r.on_start(fn) / r.on_stop(fn) on Router):
import * as http from "cdt.http"
import * as cache from "cdt.cache"
on start {
print("app starting")
}
on stop {
print("app stopped cleanly")
}
func init_router() -> Void {
print("router starting")
}
func close_router() -> Void {
print("router stopping")
}
func hello(_req: http.Request) -> http.Response {
spawn print("background audit log")
return http.text("ok")
}
router Api {
on_start => init_router
on_stop => close_router
get "/hello" => hello
}Shutdown sequence when r.stop() is called or SIGINT (Ctrl+C) / SIGTERM is received:
- New connections are rejected and
listener.accept()wakes up immediately. - In-flight HTTP requests finish normally.
- Active
spawnbackground tasks are drained (up to 5 seconds). - Router
on_stophooks run, followed by top-levelon stophooks. - If an
on_starthook fails,servereturnsHttpError { kind: "startup_error", ... }without binding the port; if anon_stophook fails,servereturnsHttpError { kind: "shutdown_error", ... }.
TIP
To coordinate config, http, schedule, shutdown, and LIFO on start/on stop hooks in a single declaration, see cdt.app.
Declarative router DSL Example
import * as http from "cdt.http"
func check_auth(req: http.Request) -> http.Response? {
if req.path.starts_with("/admin") && (req.headers.get("authorization") ?? "") != "Bearer secret" {
return http.response(401, "unauthorized")
}
return nil
}
func add_cors(_req: http.Request, resp: http.Response) -> http.Response {
hdrs := resp.headers
hdrs.set("access-control-allow-origin", "*")
return http.response_with(resp.status, resp.body, hdrs)
}
func hello(req: http.Request) -> http.Response {
name := req.params.get("name") ?? "world"
return http.text("Hello, {name}!")
}
router Api "Demo API" {
before check_auth
after add_cors
get "/hello/:name" => hello
}
func main() -> Void {
switch http.serve<Api>("127.0.0.1:8080") {
case http.HttpError(e):
print("Server error: {e.message}")
case _:
print("stopped")
}
}Typed JSON & Validation Contracts
A route handler in a declarative router block may take a second parameter (req: http.Request, body: MyStruct) -> http.Response:
import * as http from "cdt.http"
import * as validation from "cdt.validation"
struct CreateUser {
email: String @validation.email
name: String @validation.min(2)
}
func create_user(req: http.Request, body: CreateUser) -> http.Response {
return http.response(201, "Created {body.name}")
}
router Api {
post "/users" => create_user
}When a request matches /users, the router automatically:
- Decodes
req.bodyasCreateUser(returns400 Bad RequestJSON{"error":"invalid_json","message":...}on parse/type error). - Runs all
@validation.*and custom[#validator]rules onCreateUser(returns422 Unprocessable EntityJSON{"error":"validation_failed","issues":[...]}on failure). - Invokes
create_user(req, body)with the validated struct.
The typed body parameter can also be a tagged-union data enum (decoded via its "type" discriminator field).
Route Inspection & OpenAPI 3.0.3 (conduit routes & conduit openapi)
Declarative router blocks can be inspected or exported to an OpenAPI 3.0.3 specification directly from the CLI without starting the server:
# Print the route table (METHOD, PATH, HANDLER, BODY, middleware)
conduit routes main.cdt
# Generate OpenAPI 3.0.3 JSON specification
conduit openapi main.cdt --title "Users API" --version "1.0.0" --server http://localhost:8080 -o openapi.jsonconduit openapi automatically extracts path parameters (:id, *rest), request body schemas (including @validation.* constraints and data enum oneOf + discriminator schemas), and inferred response status codes (http.ok_json, http.status_json, http.no_content, http.redirect, plus 400/422 error contracts).
Imperative Example
import * as http from "cdt.http"
func main() -> Void {
r := http.router()
r.get("/hello/:name", (req: http.Request) -> http.Response => {
name := req.params.get("name") ?? "world"
return http.text("Hello, {name}!")
})
switch r.serve("127.0.0.1:8080") {
case http.HttpError(e):
print("Server error: {e.message}")
case _:
print("stopped")
}
}