Standardbibliothek
Antra::Net::HTTP
import Antra::Net::HTTPSmall HTTP server helpers built on the phase-1 TCP socket surface.
Antra::Net::HTTP is a deliberately small server-side MVP package.
It currently focuses on one-shot request/response flows and keeps the
public API narrow:
read_request(...)parses one HTTP/1.x request line plus headers and optionally a simpleContent-Lengthbodyresponse(...)/text(...)build%HttpResponse{...}valuessse(...)builds a small%HttpSSE{...}streaming response fortext/event-streamserve(...)keeps one listener open for multiple requests and supports small concurrency modes like:sequentialand:fork_per_clientserve_once(...)binds one listener, accepts one client, answers oncefork(...)runs the same server loop in a child viaSystem.forkfork_once(...)runs the same one-shot server in a child viaSystem.fork
Current request shape:
%HttpRequest{method, target, path, version, headers, body, meta}%HttpRequestMeta{request_index, local_addr}viarequest.meta
Current response shape:
%HttpResponse{status, headers, body}%HttpSSE{status, headers, run}for small SSE streams- optional
%HttpControl{response, stop}for loop control inserve(...)
Example:
import Antra::Net::HTTP as HTTP
val %Ok[_] = HTTP.serve("127.0.0.1", 4040, |request| -> {
if (request.method == "GET" && request.path == "/") {
HTTP.ok("hello from antra\n")
} else {
HTTP.not_found()
}
}, [max_requests: 10])Typen#
typedef Concurrency = :sequential | :fork_per_client | :multiplexHow serve handles clients.
Funktionen#
anybad_jsonbad_requestbody_jsonbody_textcontroldeleteforkfork_oncegethtmljsonmethod_not_allowednot_foundokpatchpostputquery_paramquery_paramsread_requestredirectrequire_jsonresponserouterroutessend_responseserveserve_oncessesse_commentsse_eventsse_tickerstoptext
fn any(handler)Declares a catch-all fallback route for router([...]).
Returns %HttpRouteAny{handler}.
fn bad_json()
fn bad_json(body)Convenience constructor for invalid JSON request bodies.
Returns %HttpResponse{status, headers, body}.
fn bad_request()
fn bad_request(body)Convenience constructor for 400 Bad Request.
Returns %HttpResponse{status, headers, body}.
fn body_json(request)
fn body_json(request, opts)Parses the request body as JSON.
Returns %Ok[value] or %Err[%Error{...}].
fn body_text(request)Returns the raw request body text.
Expects %HttpRequest{...} and returns its current in-memory body as string.
fn control(http_response)
fn control(http_response, [stop: stop = false, ..])Wraps a response with explicit loop control metadata.
Expects %HttpResponse{...} and returns %HttpControl{response, stop}.
fn delete(path, handler)Declares a DELETE route for router([...]).
Returns %HttpRoute{method, path, handler}.
fn fork(host, port, handler)
fn fork(host, port, handler, [max_requests: max_requests = undef, concurrency: concurrency = :sequential, ..])Forks a child process that runs serve_once(...) and exits afterwards.
The parent receives %Ok[#Process<...>] or %Err[%Error{...}].
fn fork_once(host, port, handler)Forks a child process that runs serve_once(...) and exits afterwards.
The parent receives %Ok[#Process<...>] or %Err[%Error{...}].
fn get(path, handler)Declares a GET route for router([...]).
Returns %HttpRoute{method, path, handler}.
fn html(body)
fn html(status, body)Builds a text/html response with UTF-8 charset.
Returns %HttpResponse{status, headers, body}.
fn json(value)
fn json(status, value)Builds a JSON response from an Antra value.
Returns %HttpResponse{status, headers, body}.
fn method_not_allowed()
fn method_not_allowed(body)Convenience constructor for 405 Method Not Allowed.
Returns %HttpResponse{status, headers, body}.
fn not_found()
fn not_found(body)Convenience constructor for 404 Not Found.
Returns %HttpResponse{status, headers, body}.
fn ok(body)Convenience constructor for 200 OK text responses.
Returns %HttpResponse{status, headers, body}.
fn patch(path, handler)Declares a PATCH route for router([...]).
Returns %HttpRoute{method, path, handler}.
fn post(path, handler)Declares a POST route for router([...]).
Returns %HttpRoute{method, path, handler}.
fn put(path, handler)Declares a PUT route for router([...]).
Returns %HttpRoute{method, path, handler}.
fn query_param(request, key)
fn query_param(request, key, default)Reads one decoded query parameter or returns undef when absent.
fn query_params(request)Parses the request query string into a decoded string-keyed map.
Returns %{...}. Repeated keys currently use the last value.
fn read_request(socket)
fn read_request(socket, [request_index: request_index = undef, ..])Parses one HTTP request from a connected socket.
Returns %Ok[%HttpRequest{method, target, path, version, headers, body, meta}]
or %Err[message].
fn redirect(location)
fn redirect(status, location)Builds a redirect response with Location header.
Returns %HttpResponse{status, headers, body}.
fn require_json(request, opts = [], on_error = bad_json())Parses the request body as JSON and maps parse failures to a 400 response.
Returns %Ok[value] or %Err[%HttpResponse{status, headers, body}].
on_error should itself be a %HttpResponse{...} value.
fn response(status, body)
fn response(status, body, headers)Builds a plain %HttpResponse{...} value.
Returns %HttpResponse{status, headers, body}.
fn router(route_defs)Builds a small router from helper routes such as HTTP.get(...).
Returns a handler function request -> %HttpResponse{...}.
fn routes(route_defs)
fn routes(route_defs, [fallback: fallback = _default_route_fallback, ..])Builds a small exact-match router from [method, path, handler] entries.
Returns a handler function request -> %HttpResponse{...}.
fn send_response(socket, http_response)Renders and sends one %HttpResponse{...} or %HttpSSE{...} over a connected socket.
Returns %Ok[undef] or %Err[%Error{...}].
fn serve(host, port, handler)
fn serve(host, port, handler, [max_requests: max_requests = undef, concurrency :- Concurrency = :sequential, ..])Opens one listener, accepts one client, parses one request and answers once.
The handler(request) callback may return %HttpResponse{...},
%HttpSSE{...} or %HttpControl{response, stop}.
Returns %Ok[undef] or %Err[%Error{...}] / %Err[message].
fn serve_once(host, port, handler)Opens one listener, accepts one client, parses one request and answers once.
The handler(request) callback may return %HttpResponse{...},
%HttpSSE{...} or %HttpControl{response, stop}.
Returns %Ok[undef] or %Err[%Error{...}] / %Err[message].
fn sse(run)
fn sse(run, [status: status = 200, headers: headers = %{}, ..])Builds a small Server-Sent Events response.
Returns %HttpSSE{status, headers, run}.
fn sse_comment(writer, text)Sends one SSE comment frame over an active SSE writer.
Returns %Ok[Number] from the underlying socket send or %Err[%Error{...}].
fn sse_event(writer, data)
fn sse_event(writer, data, [event: event = undef, id: id = undef, retry: retry = undef, ..])Sends one SSE event frame over an active SSE writer.
Returns %Ok[Number] from the underlying socket send or %Err[%Error{...}].
fn sse_ticker(state, tick)
fn sse_ticker(state, tick, [
status: status = 200,
headers: headers = %{},
tick_ms: tick_ms = 250,
keepalive_ms: keepalive_ms = undef,
max_age_ms: max_age_ms = undef,
..
])Builds a resumable Server-Sent Events response.
Unlike sse(...), whose callback runs until the stream ends, tick is
called once per due round and must return immediately with one of
%Emit[data, next_state], %Emit[data, next_state, opts],
%Idle[next_state] or %Done[]. That is what lets :multiplex keep
many streams open in one process; the blocking modes drive the same
ticker in a loop, so one handler works in every mode.
opts takes the same event:, id: and retry: keys as sse_event.
keepalive_ms: writes a comment when nothing was sent for that long,
max_age_ms: closes the stream so the browser reconnects via retry.
Returns %HttpSSETicker{...}.
Example:
HTTP.sse_ticker(0, |seen| -> match latest() {
%Some[n] when n > seen -> %Emit[str(n), n, [event: "tick", id: str(n)]]
_ -> %Idle[seen]
}, [tick_ms: 250, keepalive_ms: 15000])fn stop(http_response)Signals that serve(...) / fork(...) should stop after this response.
Expects %HttpResponse{...} and returns %HttpControl{response, stop: true}.
fn text(status, body)Builds a text/plain response with UTF-8 charset.
Returns %HttpResponse{status, headers, body}.
