Skip to content

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 ​

conduit
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 }
  • Router
  • Client — Reusable HTTP/1.1 client with base URL, default headers, configurable timeout, and a thread-safe Keep-Alive TCP/TLS connection pool.

Module Functions ​

FunctionSignatureDescription
routerhttp.router() -> RouterCreates a new HTTP router.
clienthttp.client(base_url?: String) -> ClientCreates a pooled keep-alive http.Client with an optional base_url (default timeout 30000 ms).
buildhttp.build<T>() -> RouterInstantiates a Router from a declarative router Name { ... } schema.
servehttp.serve<T>(addr: String) -> Void | HttpErrorBuilds and starts a blocking multi-threaded HTTP/1.1 server from a declarative router Name { ... } schema.
texthttp.text(body: String) -> Response200 OK with text/plain; charset=utf-8.
htmlhttp.html(body: String) -> Response200 OK with text/html; charset=utf-8.
jsonhttp.json(body: String) -> Response200 OK with application/json.
ok_jsonhttp.ok_json(val: T) -> ResponseEncodes val as JSON and returns 200 OK (application/json).
status_jsonhttp.status_json(status: Int, val: T) -> ResponseEncodes val as JSON with custom HTTP status.
redirecthttp.redirect(url: String, status?: Int) -> ResponseRedirect response (302 by default) with location header.
no_contenthttp.no_content() -> Response204 No Content empty response.
responsehttp.response(status: Int, body: String) -> ResponseCustom status code and body.
response_withhttp.response_with(status: Int, body: String, headers: Map<String, String>) -> ResponseCustom status code, body, and headers.
cookiehttp.cookie(name: String, value: String) -> CookieCreates a Cookie builder (path="/", http_only=true, secure=false, same_site="Lax", max_age=-1).
gethttp.get(url: String) -> Response | HttpErrorSends an HTTP/HTTPS GET request (follows up to 10 redirects; http:// and https:// via built-in TCP/TLS client).
posthttp.post(url: String, body: String) -> Response | HttpErrorSends an HTTP POST request with body.
get_jsonhttp.get_json<T>(url: String, query?: Map<String, String>) -> T | HttpErrorSends GET (Accept: application/json), appends optional URL-encoded query, and decodes JSON into T.
post_jsonhttp.post_json(url: String, body: T) -> Response | HttpErrorEncodes body as JSON and sends POST with Content-Type: application/json.
requesthttp.request(method: String, url: String, body: String, headers: Map<String, String>) -> Response | HttpErrorSends a custom HTTP request with method, body, and headers.
request_timeouthttp.request_timeout(method: String, url: String, body: String, headers: Map<String, String>, timeout_ms: Int) -> Response | HttpErrorSends a custom HTTP request with an explicit timeout in milliseconds.
get_byteshttp.get_bytes(url: String) -> BinaryResponse | HttpErrorSends an HTTP GET request and returns a BinaryResponse with a Bytes body.
request_byteshttp.request_bytes(method: String, url: String, body: Bytes | [Int], headers: Map<String, String>) -> BinaryResponse | HttpErrorSends 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.

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:

conduit
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", "/")?
HelperSignatureDescription
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_cookieresp.set_cookie(cookie: Cookie) -> Response | HttpErrorValidates name, value, path, domain, and same_site ("invalid_cookie") and appends a Set-Cookie line.
resp.clear_cookieresp.clear_cookie(name: String, path?: String) -> Response | HttpErrorAppends an expired Max-Age=0; Expires=Thu, 01 Jan 1970 00:00:00 GMT Set-Cookie header (default path = "/").
resp.cookies / .cookieresp.cookies() -> Map<String, String>, resp.cookie(name: String) -> String?Parses Set-Cookie headers received by client or middleware responses.
req.cookies / .cookiereq.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: parses application/x-www-form-urlencoded bodies (%XX and + decoding, strict UTF-8, up to 1024 fields, "invalid_content_type" if another Content-Type header 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: parses multipart/form-data completely in memory with zero implicit disk writes (defaults: 10 MiB max payload, 64 parts). Quoted boundaries are supported. Uploaded filenames in UploadedFile.filename have directory prefixes (/ and \), quotes, and control bytes stripped (. / .. map to ""). Access text fields via form.fields, repeated fields via form.fields_all(name) -> [String], and uploaded files via form.files: [UploadedFile]. If you save uploads to disk, pass file.data (Bytes) explicitly to cdt.fs so runtime --allow-write sandbox 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.

MethodSignatureDescription
headerc.header(name: String, value: String) -> ClientReturns a client copy (sharing the same pool) with default header name: value.
bearerc.bearer(token: String) -> ClientSets Authorization: Bearer <token> on the client.
timeout_msc.timeout_ms(ms: Int) -> ClientSets request timeout in milliseconds.
base_urlc.base_url(url: String) -> ClientUpdates the client's base_url.
deny_private_addrsc.deny_private_addrs(enabled?: Bool) -> ClientBlocks 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.
getc.get(path: String) -> Response | HttpErrorPooled GET against base_url + path (or full URL).
deletec.delete(path: String) -> Response | HttpErrorPooled DELETE request.
postc.post(path: String, body: String) -> Response | HttpErrorPooled POST request with string body.
putc.put(path: String, body: String) -> Response | HttpErrorPooled PUT request with string body.
patchc.patch(path: String, body: String) -> Response | HttpErrorPooled PATCH request with string body.
get_jsonc.get_json<T>(path: String, query?: Map<String, String>) -> T | HttpErrorPooled GET (Accept: application/json) decoding JSON into T.
post_jsonc.post_json(path: String, body: T) -> Response | HttpErrorPooled POST encoding body as JSON (Content-Type: application/json).
requestc.request(method: String, path: String, body?: String, headers?: Map<String, String>) -> Response | HttpErrorPooled custom request with optional body and per-request headers.
pool_statsc.pool_stats() -> Map<String, Int>Returns pool metrics ({"idle": <count>}).
closec.close() -> VoidCloses and drains all idle connections in the client's pool.
conduit
api := http.client("https://api.example.com")
    .bearer(token)
    .timeout_ms(5000)

user := api.get_json<User>("/v1/me")?
api.close()

Router Methods ​

MethodSignatureDescription
get, post, put, delete, patch, options, head, anyr.<method>(pattern: String, handler: (Request) -> Response) -> VoidRegisters a route (/users/:id, /files/*rest; any matches all methods).
beforer.before(handler: (Request) -> Response?) -> VoidRegisters a pre-handler hook; returning a Response short-circuits routing.
afterr.after(handler: (Request, Response) -> Response) -> VoidRegisters a post-handler hook to transform responses (e.g. CORS headers, logging).
on_startr.on_start(handler: () -> Void | Error) -> VoidRegisters a startup hook executed before binding the listener in r.serve(...).
on_stopr.on_stop(handler: () -> Void | Error) -> VoidRegisters a shutdown hook executed after draining in-flight requests and spawn tasks.
dispatchr.dispatch(req: Request) -> ResponseDispatches a Request in-memory (returns 404/405 automatically).
server.serve(addr: String) -> Void | HttpErrorStarts a blocking HTTP/1.1 server on addr (e.g. "127.0.0.1:8080") with SIGINT/SIGTERM graceful shutdown.
stopr.stop() -> VoidSignals r.serve(...) to stop accepting new connections and shut down gracefully after in-flight requests finish.
workersr.workers(count: Int) -> VoidConfigures the HTTP server worker thread count (1..=256). Overridden by CONDUIT_HTTP_WORKERS.
timeoutsr.timeouts(idle_ms: Int, header_ms: Int, body_ms: Int) -> VoidConfigures 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_ipr.max_conns_per_ip(limit: Int) -> VoidConfigures max concurrent connections per remote IPv4 address / IPv6 /64 prefix (0 disables per-IP limit). Overridden by CONDUIT_HTTP_MAX_CONNS_PER_IP.
trusted_proxiesr.trusted_proxies(cidrs: [String]) -> VoidList 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; default clamp(cpus, 4, 16))
  • CONDUIT_HTTP_IDLE_TIMEOUT_MS (100..=300000; default 3000)
  • CONDUIT_HTTP_HEADER_TIMEOUT_MS (500..=300000; default 10000)
  • CONDUIT_HTTP_BODY_TIMEOUT_MS (500..=600000; default 30000)
  • CONDUIT_HTTP_MAX_CONNS_PER_IP (default max(workers / 2, 4); 0 disables)
  • CONDUIT_HTTP_MAX_CONNS (16..=65536; reactor global concurrent connection cap, default clamp(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 ​

MethodSignatureDescription
headerreq.header(name: String) -> String?Case-insensitive header lookup.
paramreq.param(name: String) -> String?Route :param / *wildcard lookup.
query_paramreq.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 local before/after middleware scoped to that prefix.
  • guard auth_user { get "/me" => me } — Typed route guard block: auth_user(req: http.Request) -> Ctx | http.Response short-circuits on http.Response or passes Ctx as the last typed parameter to handlers inside the block.
  • @http.query struct binding — Annotate a struct with @http.query to automatically parse and validate :param path parameters and ?key=val query parameters (with defaults and @validation.* -> 400 invalid_query / 422 validation_failed). Handlers can accept (http.Request, QueryStruct), (http.Request, QueryStruct, BodyStruct), and/or GuardCtx.
  • @http.status(code) & typed return/error unions — Handlers can return any JSON-serializable type T, Void (204), T? (200/404), http.Response, or a union T | AppError directly; annotate error or struct types with @http.status(404) (unannotated error defaults to 500, struct defaults to 200). Both @http.query parameters and typed return/error responses are reflected in conduit openapi.
  • static "/assets" => "./public" — Serves static files with Content-Type detection and path-traversal protection.
  • cors "*" — Automatically handles OPTIONS preflight (204) and injects access-control-allow-origin on responses.
  • on_start => init_fn / on_stop => cleanup_fn (or on start => ... / on stop => ...) — Router-scoped lifecycle hooks (() -> Void or () -> 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):

conduit
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:

  1. New connections are rejected and listener.accept() wakes up immediately.
  2. In-flight HTTP requests finish normally.
  3. Active spawn background tasks are drained (up to 5 seconds).
  4. Router on_stop hooks run, followed by top-level on stop hooks.
  5. If an on_start hook fails, serve returns HttpError { kind: "startup_error", ... } without binding the port; if an on_stop hook fails, serve returns HttpError { 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 ​

conduit
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:

conduit
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:

  1. Decodes req.body as CreateUser (returns 400 Bad Request JSON {"error":"invalid_json","message":...} on parse/type error).
  2. Runs all @validation.* and custom [#validator] rules on CreateUser (returns 422 Unprocessable Entity JSON {"error":"validation_failed","issues":[...]} on failure).
  3. 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:

bash
# 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.json

conduit 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 ​

conduit
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")
    }
}