March Docs

HttpServer

HttpServer module: server-side HTTP types and pipeline runner.

Built on top of Http (for Method, Header types) and WebSocket modules. Provides the Conn type, pipeline composition, and server startup.

Usage: HttpServer.new(4000) |> HttpServer.max_connections(500) |> HttpServer.idle_timeout(30) |> HttpServer.plug(logger) |> HttpServer.plug(router) |> HttpServer.listen()

Types

typeUpgradeUpgrade = NoUpgrade | WebSocketUpgrade(WsSocket -> Unit)#

Upgrade type for WebSocket connections

typeConnConn = Conn(#

The Conn type: holds everything about a request-response cycle. Modeled on Plug.Conn from Elixir. The method field is an Atom (e.g. :get, :post) — interned i64 hash, allocation-free and safe for pattern matching in compiled mode.

typeTlsSourceTlsSource = TlsFiles(String, String) | TlsPem(String, String)#

Where an HTTPS server's certificate and private key come from: TlsFiles(cert_path, key_path) reads PEM files (a full chain, leaf first, such as certbot's fullchain.pem, and its key); TlsPem(cert, key) takes the PEM text itself.

typeServerOptsServerOpts = ServerOpts(#

HTTPS and timeout options, set by the builders below. The tls field holds the call that configures TLS (built by tls, given the poll interval and the bootstrap flag), not the TlsSource itself, so a plain-HTTP program never references the TLS builtin and links no OpenSSL (runtime/march_tls_ops.h).

typeServerServer = Server(#

Server config type

Functions

fnacme_responderacme_responder(lookup)#

A plug that answers ACME HTTP-01 challenges from memory: for GET /.well-known/acme-challenge/<token> it calls lookup(token) and responds 200 text/plain with Some(key_authorization), or 404 for None. Tokens outside the base64url alphabet are 404 without a lookup. Other requests pass through untouched.

Examples

HttpServer.plain_listener(server, 80, [
  HttpServer.acme_responder(fn token -> Vault.get(challenges, token)),
  HttpServer.redirect_to_https(443)
])
fnassignassign(conn, key, value)#

Store a key/value pair in the conn's assigns (a per-request store plugs use to pass data along the pipeline). Later assignments to the same key shadow earlier ones for get_assign; all are kept in assigns.

fnassignsassigns(conn)#

All assigns as a List((String, String)), most recent first (see assign).

fnbind_hostbind_host(host : String) : Unit#

Bind later servers to host, a dotted IPv4 address such as "127.0.0.1", instead of every interface. Call it before listen or spawn_n; it panics on anything that isn't an IPv4 address.

fnconn_upgradeconn_upgrade(conn)#

The conn's upgrade request: NoUpgrade (the default), or WebSocketUpgrade(handler) to hand the socket to a WebSocket handler after the pipeline.

fnfdfd(conn)#

The underlying TCP socket file descriptor of the conn.

fnget_assignget_assign(conn, key)#

Look up a value stored with assign: Some(value) for the most recent assignment to key, or None.

Examples

let conn = HttpServer.assign(conn, "user", "ann")
HttpServer.get_assign(conn, "user")   -- Some("ann")
fnget_req_headerget_req_header(conn, name)#

Look up a request header by name, case-insensitively. Returns Some(value) for the first match in req_headers order, or None.

Examples

match HttpServer.get_req_header(conn, "Authorization") do
  Some(v) -> check_token(conn, v)
  None -> HttpServer.text(conn, 401, "unauthorized")
end
fnget_resp_headerget_resp_header(conn, name)#

Look up a response header set so far, case-insensitively. Because put_resp_header prepends, this returns the most recently put value.

fnhalthalt(conn)#

Mark the conn halted without setting a response, so remaining plugs are skipped. The status stays whatever it was (0 if never set). A later send_resp on the halted conn panics.

fnhaltedhalted(conn)#

True once the conn has been responded to or halted; run_pipeline then skips the remaining plugs.

fnheader_timeoutheader_timeout(server, secs)#

Close a connection that has not sent a request's complete headers within secs seconds of its first byte (default 30).

fnhtmlhtml(conn, resp_status, body)#

Respond with an HTML body: adds content-type: text/html; charset=utf-8 and calls send_resp. Panics if the conn is already halted.

fnidle_timeoutidle_timeout(server, secs)#

Close a keep-alive connection after secs seconds with no request in progress (default 60). Applies to both server modes; an upgraded WebSocket is not subject to it.

fnjsonjson(conn, resp_status, body)#

Respond with a JSON body (already-encoded String): adds content-type: application/json and calls send_resp. Panics if the conn is already halted.

fnlistenlisten(server)#

Bind the configured port and serve requests forever with the plug pipeline (via the runtime's http_server_listen). Each request becomes a Conn; the pipeline's result is written back as the response, or handed to the WebSocket handler if conn_upgrade is a WebSocketUpgrade. Does not return in normal operation. Requires IO.NetListen.

fnmax_connectionsmax_connections(server, n)#

Set the maximum number of concurrent connections (default 1000).

fnmethodmethod(conn)#

Return the request method atom (:get, :post, …) of a Conn.

fnmethod_to_stringmethod_to_string(m)#

Convert a request-method atom to its uppercase string name, suitable for logging, response bodies, or rebuilding a request line. Returns "UNKNOWN" for any atom that is not one of the recognized HTTP verbs. Atoms use lowercase by convention: :get, :post, :put, :patch, :delete, :head, :options, :trace, :connect.

Examples

march> HttpServer.method_to_string(:get)
"GET"
march> HttpServer.method_to_string(:patch)
"PATCH"
march> HttpServer.method_to_string(:not_a_verb)
"UNKNOWN"
fnnewnew(port)#

A server config listening on port with no plugs, max_connections

  1. Nothing is bound until listen or

spawn_n.

Examples

HttpServer.new(4000)
|> HttpServer.plug(fn conn -> HttpServer.text(conn, 200, "ok"))
|> HttpServer.listen()
fnpathpath(conn)#

The raw request path without the query string, e.g. /users/42.

fnpath_infopath_info(conn)#

The request path split on / with empty segments removed: /users/42/ gives a two-element list of users and 42.

fnpeer_addrpeer_addr(conn)#

Return the numeric IP address of the connected peer (the socket's remote address), e.g. "203.0.113.7" or "2001:db8::1".

This is the transport-level address — it cannot be spoofed by request headers, unlike X-Forwarded-For. Behind a reverse proxy it is the proxy's address, not the end client's.

Returns "" when no live socket backs the conn (e.g. test conns).

fnplain_listenerplain_listener(server, port, plugs)#

Also serve plain HTTP on port, with its own plugs, from the same listen. Typical use on an HTTPS server: answer ACME challenges and redirect everything else.

Examples

HttpServer.new(443)
|> HttpServer.tls(HttpServer.TlsFiles(cert, key))
|> HttpServer.plain_listener(80, [HttpAcme.webroot("/var/www/acme"),
                                  HttpServer.redirect_to_https(443)])
|> HttpServer.plug(router)
|> HttpServer.listen()
fnplugplug(server, p)#

Append a plug (Conn -> Conn) to the end of the server's pipeline. Plugs run in the order they were added.

fnprogress_timeoutprogress_timeout(server, secs)#

Close a connection when reading a request body or writing a response makes no progress for secs seconds (default 30). A slow transfer that keeps moving is never cut.

fnput_resp_headerput_resp_header(conn, name, value)#

Add a response header. The header is prepended and existing headers with the same name are NOT replaced, so putting a name twice sends it twice.

fnquery_stringquery_string(conn)#

The raw query string after the ?, e.g. page=1&limit=10; empty when the URL has none.

fnredirectredirect(conn, url)#

Respond 302 Found with a location: url header and an empty body. Panics if the conn is already halted.

fnredirect_to_httpsredirect_to_https(port)#

A plug that redirects every request to the same URL over HTTPS on port: https://<Host without its port>[:port unless 443]<path>[?query]. GET and HEAD get 301; other methods get 308 so the method and body are kept. A request without a Host header gets 400. ACME challenge paths (/.well-known/acme-challenge/) pass through, so it works before or after HttpAcme.webroot in a plain_listener.

Examples

HttpServer.new(443)
|> HttpServer.tls(HttpServer.TlsFiles(cert, key))
|> HttpServer.plain_listener(80, [HttpServer.redirect_to_https(443)])
fnreload_tlsreload_tls(src)#

Install a new certificate and key on the running HTTPS server. New connections use it; open ones keep the one they started with. A pair that does not load, does not match, or has expired is refused with Err and the current certificate stays. Needs IO.NetListen, like serving.

fnreq_bodyreq_body(conn)#

The request body (the Content-Length bytes) as a String; empty when there is none.

fnreq_headersreq_headers(conn)#

All request headers as a List(Header). The runtime builds the list by prepending, so it is in reverse wire order.

fnresp_bodyresp_body(conn)#

The response body set so far; empty until a response is sent.

fnresp_headersresp_headers(conn)#

The response headers set so far, most recently put first.

fnrun_pipelinerun_pipeline(conn, plugs)#

Run a list of plugs (Conn -> Conn functions) in order, threading the conn through. Before each plug the conn is checked: once it is halted the remaining plugs are skipped and the halted conn is returned.

Examples

HttpServer.run_pipeline(conn, [logger, auth, router])
fnschemescheme(conn)#

`\

fnsend_respsend_resp(conn, resp_status, body)#

Set the response status and body and mark the conn halted. This is the primary way to respond; later plugs in the pipeline are skipped. The response is written by the runtime after the pipeline returns.

Panics if the conn is already halted (by send_resp, a helper such as text/json, or halt): a double response is always a handler bug, and silently overwriting the first reply would mask it.

Examples

conn
|> HttpServer.put_resp_header("cache-control", "no-store")
|> HttpServer.send_resp(200, "ok")
fnspawn_nspawn_n(server, n)#

Start the server in a forked subprocess that handles exactly n requests and then exits. Returns a handle (the child PID) for wait_for. A readiness pipe makes the call return only after the child has bound the port, so the caller can connect immediately. Intended for tests.

Examples

let h = HttpServer.new(18080)
  |> HttpServer.plug(fn conn -> HttpServer.text(conn, 200, "pong"))
  |> HttpServer.spawn_n(1)
let resp = HttpClient.get(HttpClient.new_client(), "http://127.0.0.1:18080/")
HttpServer.wait_for(h)
fnstatusstatus(conn)#

The response status set so far: 0 until send_resp or a helper sets it. A conn returned with status 0 is sent as 200.

fntexttext(conn, resp_status, body)#

Respond with a plain-text body: adds content-type: text/plain; charset=utf-8 and calls send_resp. Panics if the conn is already halted.

Examples

fn hello(conn) do
  HttpServer.text(conn, 200, "hello, " ++ HttpServer.path(conn))
end
fntlstls(server, src)#

Serve HTTPS on the server's port with the certificate and key from src. listen refuses to start (it panics, naming the file and the reason) when they cannot be loaded or do not match, unless tls_wait_for_cert was set and the files are merely missing. An expired certificate at startup is served with a warning. With TlsFiles, the files are re-read every tls_poll_interval seconds and a renewed pair is picked up without a restart. Needs a compiled build (march --compile, forge build).

Examples

HttpServer.new(443)
|> HttpServer.tls(HttpServer.TlsFiles(
     "/etc/letsencrypt/live/example.com/fullchain.pem",
     "/etc/letsencrypt/live/example.com/privkey.pem"))
|> HttpServer.plug(router)
|> HttpServer.listen()
fntls_handshake_timeouttls_handshake_timeout(server, secs)#

Close a connection whose TLS handshake has not finished within secs seconds (default 10).

fntls_poll_intervaltls_poll_interval(server, secs)#

Re-read the TlsFiles certificate pair every secs seconds (default 60) and install it when its content changed. 0 turns polling off; reload_tls still works.

fntls_wait_for_certtls_wait_for_cert(server)#

Bootstrap mode for a first certificate: when the TlsFiles do not exist yet, listen starts anyway, serving only the plain_listener (where an ACME challenge can be answered), and binds the HTTPS port as soon as the poller or reload_tls installs a valid pair. Files that exist but are invalid still stop listen.

fnwait_forwait_for(handle)#

Block until the server subprocess started by spawn_n (given its handle) exits.