Atom

http.serve()

Processes one HTTP request per accepted connection.

Signature

http.serve(listener, handler[, request_limit[, max_body]])

Parameters

Open TCP listener, handler(request), optional nonnegative signed request count (default unlimited), and optional nonnegative signed body cap (default 8 MiB).

Returns

Unsigned number of processed connections on success.

Behavior

Handler takes method, target, headers and body. Return null, text, packed data or a dictionary with status (200–599, default 200), headers and body. Response headers accept repeated values via arrays. Connection, Content-Length and Transfer-Encoding are generated/reserved. HEAD, 204 and 304 suppress bodies. The server closes each accepted connection. The caller owns the listener.

Errors

Listener or I/O errors, handler failure (attempts a 500 response), invalid response. Malformed requests may receive 400, 413, 417 or 431 and the loop can continue.

Example

Run this one-request server on loopback and connect with the HTTP client using port 18080.

Atom
use http
use net

func respond(request):
    return 'Received {request.target}'

listener = http.listen('127.0.0.1', 18080, {timeout = 10})
try:
    assert(http.serve(listener, respond, 1, 4096) == 1)
finally:
    net.close(listener)