Web servers: http.server
A web server answers requests from browsers and other programs. In Luma you write a function for each page or API endpoint, list them in routes, and start the server. It is built in; no import is needed.
A server in ten lines
fn home(req: http.request): http.response {
return http.text("Hello, world")
}
fn user(req: http.request): http.response {
return http.json({"id": req.params["id"]})
}
routes: [http.route] = [
http.get("/", home),
http.get("/users/:id", user),
]
http.serve(8080, routes)Run it with luma run app.luma, or build it with luma build, and open http://localhost:8080/users/42:
Listening on http://localhost:8080The server goes on until the program is stopped (Ctrl+C).
Handlers
A handler is a function that takes the request and gives the response: fn name(req: http.request): http.response. Its type has a name, http.handler.
req. | Holds |
|---|---|
method | "GET", "POST", … |
path | the path, decoded: "/users/42" |
params | the parts the route names: /users/:id gives {"id": "42"} |
query | the query, decoded: ?page=2&q=a+b gives {"page": "2", "q": "a b"} |
headers | the headers, with their names in lower case |
body | the body, a str |
json() | the body read as JSON |
form() | the fields of a form (application/x-www-form-urlencoded, or a multipart/form-data form’s fields that aren’t files) |
files() | the files sent with a form, a [http.upload]: see File uploads |
cookies | the cookies the browser sent, by name: req.cookies["theme"] |
session() | the visitor’s session: see Cookies and sessions |
The response is made with one of these, or written out as http.response { status: 201, body: "..." }:
| Function | Gives |
|---|---|
http.text(text) | 200 with text (text/plain) |
http.html(page) | 200 with an HTML page (text/html) |
http.json(value) | 200 with the JSON of a json value (application/json) |
http.file(path) | 200 with a file, its Content-Type by its extension (.html, .png, .pdf, …); 404 if there is no such file |
http.bytes(data, kind) | 200 with bytes (a [byte], buffer or str) of the type kind, "image/png" say; without kind, application/octet-stream |
http.status(code, text) | any status, with text |
http.redirect(url) | 302 to url |
res.header(name, value) adds a header to a response before it is returned, res.status changes its status, and res.cookie(name, value) sets a cookie:
fn page(req: http.request): http.response {
res: http.response = http.text("cached for an hour")
res.header("Cache-Control", "max-age=3600")
return res
}A file to download, with the name the browser saves it as:
fn report(req: http.request): http.response {
res: http.response = http.file("reports/2026.pdf")
res.header("Content-Disposition", "attachment; filename=\"report-2026.pdf\"")
return res
}HTML pages
Text that comes from outside (what a user typed, a query, a database) goes into a page through http.escape(text). It turns &, <, >, " and ' into &, <, >, " and ', so a name like <script>...</script> shows as text instead of running in the visitor’s browser (cross-site scripting):
fn hello(req: http.request): http.response {
name: str = http.escape(req.params["name"])
res: http.response = http.html("<h1>Hello, ${name}</h1>")
if name == "" {
res.status = 404
}
return res
}http.escape is for an element’s text and for attribute values in quotes (title="${http.escape(t)}"); it doesn’t make text safe inside <script>, a style, or a URL (href) that a visitor gives.
http.html also takes an html value: a page loaded from a file and filled in by its methods, which escape what they put in by themselves. See Pages from templates.
File uploads
A form with enctype="multipart/form-data" sends files. req.files() gives them, and req.form() the form’s other fields:
<form method="post" action="/photos" enctype="multipart/form-data">
<input name="title">
<input type="file" name="photo" multiple>
<button>Send</button>
</form>fn photos(req: http.request): http.response {
title: str = req.form()["title"]
req.files().walk(f) {
file("uploads/${uuid.v4()}.jpg").write(f.data)
print("${f.name}: ${len(f.data)} bytes")
}
return http.html("<p>Saved ${http.escape(title)}</p>")
}http.upload | Holds |
|---|---|
field | the form field’s name: "photo" |
name | the file’s name on the visitor’s computer, without folders: "beach.jpg" |
kind | the type the browser says it is: "image/jpeg" |
data | its bytes, a [byte] |
- Several files in one field (
multiple) come as several uploads with the samefield, in the order they were sent. A file input left empty sends nothing. nameandkindcome from the visitor, so don’t trust them:namehas no folders (../../etc/passwdispasswd), but can still be anything, andkindis only what the browser claims. Save files under a name of your own (auuid.v4(), say) and check the bytes if their type matters.- Bodies are at most 32 MB, or what
max_bodysays: a bigger one is answered413 Content Too Largebefore it is read. A form that isn’t valid multipart raises error 11 (invalid multipart form: ...), whichon_errorcan answer with 400. - The whole body is in memory while the handler runs; for files of hundreds of megabytes, raise
max_bodywith care.
Cookies and sessions
A cookie is a small value the browser keeps for a site and sends back with every request to it. res.cookie(name, value, age) sets one, req.cookies has those the browser sent, and res.forget(name) deletes one:
fn settings(req: http.request): http.response {
theme: str = "light"
if has(req.cookies, "theme") {
theme = req.cookies["theme"]
}
res: http.response = http.html("<p>Theme: ${http.escape(theme)}</p>")
res.cookie("theme", "dark", 365 * 86400) // a year; without an age, until the browser closes
return res
}Cookies that res.cookie sets are safe by default: for the whole site (Path=/), out of reach of the page’s JavaScript (HttpOnly), not sent along with forms from other sites (SameSite=Lax, which stops most cross-site request forgery), and, when the server is https, only over encrypted connections (Secure). Any text can be a value: what a cookie can’t hold is encoded, and req.cookies decodes it. For a cookie with other attributes (a Domain, readable by scripts), write the line yourself: res.header("Set-Cookie", "..."); each such header is sent on its own.
Sessions
A session keeps what the server knows about a visitor between requests, like who logged in. req.session() gives it; its data stays in the server, and the browser holds only a random ID in the cookie session:
fn password_ok(user: str, password: str): bool {
hash: str = "..." // the user's crypto.password(...), from the database
return crypto.verify(password, hash)
}
fn login(req: http.request): http.response {
f: {str: str} = req.form()
if !password_ok(f["user"], f["password"]) {
return http.status(401, "Wrong user or password")
}
s: http.session = req.session()
s.renew()
s.set("user", f["user"])
return http.redirect("/")
}
fn home(req: http.request): http.response {
user: ?str = req.session().get("user")
if user == nil {
return http.redirect("/login")
}
return http.html("<p>Hello, ${http.escape(user)}</p>")
}
fn logout(req: http.request): http.response {
req.session().clear()
return http.redirect("/login")
}http.session | Does |
|---|---|
get(key) | the value kept under key, a ?str: nil if there is none |
set(key, value) | keeps a str under key |
remove(key) | lets go of key |
renew() | gives the session a new ID, keeping its data: call it when someone logs in, so an ID someone else knew before (session fixation) is no use |
clear() | empties the session and deletes its cookie: logging out |
- A visitor gets a cookie only once something is kept: reading an empty session sets nothing.
- Sessions last 7 days without being used, or
session_ageseconds; each use starts the time again. The ID is 32 random bytes fromcrypto.random, so it can’t be guessed. - Values are
strs. Keep a user’s ID and look the rest up in a database; a session is not the place for much data. - They are in the server’s memory: a restarted server has none (everyone logs in again), and two server processes don’t share them.
Routes
http.get(path, handler), http.post, http.put, http.patch and http.delete make an http.route. The routes are tried in order, and the first that fits the method and the path answers.
:namein a path matches one part and puts it inreq.params:/users/:id/posts/:post.*at the end matches the rest:/files/*givesreq.params["*"]="a/b/c.txt"for/files/a/b/c.txt.- A
getroute answersHEADtoo, without the body. - A path no route fits gets 404 Not Found; a path that fits, with another method, 405 Method Not Allowed (with an
Allowheader).
A server with everything
http.serve(port, routes) is the short form. http.server has the rest:
fn log(req: http.request, next: http.handler): http.response {
res: http.response = next(req)
print("${req.method} ${req.path} ${res.status}")
return res
}
fn oops(req: http.request, err: error): http.response {
return http.status(500, "Something went wrong")
}
fn home(req: http.request): http.response {
return http.text("Hello")
}
server: http.server = http.server {
port: 8080,
routes: [http.get("/", home)],
middleware: [log],
files: {"/static": "public"},
on_error: oops,
}
server.start()| Field | Is | If not given |
|---|---|---|
port | the port to listen on | 8080 |
host | the address to listen on: "127.0.0.1" (or "localhost") for this computer only, another IPv4 address of it | "": all addresses |
routes | the [http.route] | none: every path is 404 |
middleware | [http.middleware], see below | none |
files | folders of files to serve, by path: {"/static": "public"} | none |
on_error | fn(http.request, error): http.response, for an error a handler raises | 500 Internal Server Error |
limit | how many requests to answer before start returns (for tests and scripts) | 0: no end |
cert, key | serve https with this certificate and private key: see https | http:// |
https | true: serve https with a self-signed certificate made at the start | false |
session_age | how many seconds a session is kept without being used | 604800 (7 days) |
max_body | the largest request body in bytes: a bigger one gets 413 (0: no limit) | 32 MB |
compress | true: gzip answers for clients that take it (Accept-Encoding: gzip): text, HTML, CSS, JavaScript, JSON, XML and SVG of 1 KB or more | false |
Middleware
Middleware is code that runs around every handler: logging, checking a login, adding headers. A middleware takes the request and next, the rest of the way to the handler: fn name(req: http.request, next: http.handler): http.response. Its type is http.middleware.
fn need_login(req: http.request, next: http.handler): http.response {
if !has(req.headers, "authorization") {
return http.status(401, "Please log in") // next isn't called: the handler doesn't run
}
return next(req)
}The first in the list is the outermost: with [log, need_login], log sees the 401 that need_login gives. Middleware also runs for paths no route fits (with a 404 from next), but not for 405s or files.
Server-sent events
A stream of events keeps the connection open and sends to the client as things happen: progress, notifications, a live feed. In a browser, new EventSource("/ticks") receives them. An events route’s handler gets the request and an http.stream, and sends with out.send:
fn ticks(req: http.request, out: http.stream) {
(1..10).walk(i) {
out.send("tick ${i}")
wait(1)
}
out.send("{\"done\": true}", "finished")
}
routes: [http.route] = [
http.events("/ticks", ticks),
]out.send(data, kind, id)writes one event at once.kind(optional) names it, so a browser can listen for it withaddEventListener("finished", ...); without one it’s amessage.id(optional) is what a reconnecting browser sends back in thelast-event-idheader. Data with several lines is sent as severaldata:lines, and arrives whole.- When the client goes, the next
sendraises error 14, which ends the handler (the server doesn’t report it).out.open()tells whether the client is still there, as far as is known; catch the error withtryto do something when it goes. - Quiet streams stay open: after 15 seconds without an event, the server sends a comment, which clients skip. That also notices a client that went.
- Middleware runs first, as for any route:
need_loginabove can answer 401 instead of the stream, and headers it adds go with the stream. - When the handler returns, the stream ends and the connection closes. The handler’s type is
http.streamer:fn(http.request, http.stream).
To send to every client, keep their streams in a list. A lambda shares the list with the routes:
listeners: [http.stream] = []
routes: [http.route] = [
http.events("/news", fn(req, out) {
listeners[] = out
while out.open() {
wait(1)
}
}),
http.post("/news", fn(req) {
listeners.walk(l) {
if l.open() {
err: error = nil
try err {
l.send(req.body)
}
}
}
return http.text("sent")
}),
]To read a stream from another server, see Event streams.
WebSockets
A WebSocket is a connection that stays open, and both sides send messages over it whenever they want: chats, games, live dashboards. In a browser, new WebSocket("ws://localhost:8080/chat") connects to it. A websocket route’s handler gets the request and an http.socket:
fn echo(req: http.request, ws: http.socket) {
while true {
msg: ?str = ws.read()
if msg == nil {
stop
}
ws.send("echo: ${msg}")
}
}
routes: [http.route] = [
http.websocket("/echo", echo),
]ws. | Does |
|---|---|
read() | waits for the next message and gives it, or nil when the connection has closed. Into a ?str a text message; into a ?[byte] or ?buffer the bytes, for binary messages |
send(x) | sends a message right away: a str as text, a [byte] or buffer as binary |
close(code, reason) | closes the connection, telling the other side why (both optional: 1000, normal) |
open() | whether it is still open |
binary | whether the last message read was binary |
code, reason | why it closed: 1000 normal, 1001 going away, 1006 dropped without a word, … |
timeout(seconds) | how long read waits at most (then error 14); without it, as long as it takes |
limit(bytes) | how big a message may be: 16 MB if not given |
- When the client goes,
read()givesnil, whether it said goodbye or just went. Asendto a closed connection raises error 14. - A quiet connection is checked: after 30 seconds without a message,
readpings the other side (it answers by itself), and givesnilif no answer comes in 30 more. - By the rules: a message too big closes it with 1009, text that isn’t UTF-8 with 1007, and frames the protocol doesn’t allow with 1002. Pings are answered, and messages sent in pieces arrive whole.
- Compressed messages: Luma’s servers and clients speak
permessage-deflate(RFC 7692) with each other and with browsers: messages of 100 bytes or more go compressed, each on its own (no context kept between messages, so a connection costs no extra memory).ws.deflatetells whether it was agreed. A message may decompress to at most 64 MB, andlimitcounts its decompressed size. - Middleware runs first: it can answer 401 instead, or check
req.headers["origin"], the page a browser connects from. - When the handler returns, the connection closes (1000). The same
http.socketis what a client gets: see WebSockets.
To send to everyone, keep the sockets in a list, as for events. A handler can send to the others while each waits in its own read:
people: [http.socket] = []
routes: [http.route] = [
http.websocket("/chat", fn(req, ws) {
people[] = ws
while true {
msg: ?str = ws.read()
if msg == nil {
stop
}
people.walk(p) {
if p.open() {
err: error = nil
try err {
p.send(msg)
}
}
}
}
}),
]Files
files: {"/static": "public"} serves the folder public under /static: /static/app.css is public/app.css, and /static/ is public/index.html. The Content-Type comes from the file’s extension (.html, .css, .js, .json, .png, .svg, …). Paths with .. are refused (404), so nothing outside the folder can be read. {"/": "public"} serves a whole site, before any routes.
https
With a certificate and its private key, the server speaks https (TLS 1.3):
server: http.server = http.server {
port: 8443,
routes: routes,
cert: "/etc/letsencrypt/live/example.com/fullchain.pem",
key: "/etc/letsencrypt/live/example.com/privkey.pem",
}
server.start()Listening on https://localhost:8443certis a PEM file with the server’s certificate first, then the authorities between it and the root, as certbot’sfullchain.pemhas them.keyis its private key in PEM, asPRIVATE KEY,EC PRIVATE KEYorRSA PRIVATE KEY: ECDSA on P-256 or P-384, or RSA. It can’t be encrypted with a password. The server checks at the start that the key belongs to the certificate.
For development, https: true without cert and key makes a self-signed certificate for localhost and 127.0.0.1 when the server starts, valid for a year, and prints its key’s pin:
server: http.server = http.server { port: 8443, routes: routes, https: true }Listening on https://localhost:8443 (self-signed certificate, key sha256//WBDpk2ieQtam7Q6EUcnqcO9Xiol4VzPygH6adtNWX5U=)A Luma program on the same computer connects to it as it is (local names accept self-signed certificates); elsewhere, the pin trusts exactly this server: req.pin("sha256//WBDp..."), or curl --pinnedpubkey sha256//WBDp... -k. Browsers warn about a self-signed certificate and let you go on.
A connection that fails before the request (a client that doesn’t speak TLS, or gives up on the certificate) is written to stderr, and the server goes on:
https: 127.0.0.1:50122 doesn't speak TLS (is it the right port?)For a busy or important site, put a proxy in front. Setting up an https connection takes the server a few milliseconds with an ECDSA key, about fifty with an RSA one, and it computes on one processor core. And its cryptography is Luma’s own: it guards the private key against timing measurements (with random blinding), but can’t promise what specialized libraries do. For a key that matters on the public internet, let nginx, Caddy or a cloud load balancer do https and pass the requests on to Luma’s http://.
HTTP/2
A server speaks HTTP/2 by itself to the clients that do: browsers and other clients choose it when connecting over https, and a client that starts with HTTP/2’s preface on plain http (h2c, which gRPC’s clients use inside a network) gets it too. The others get HTTP/1.1, on the same port. Nothing in the program changes.
- Many requests on one connection: each is answered by its handler in its own coroutine, side by side; up to 100 at once on a connection.
- The same handlers, routes and middleware:
req.method,req.path,req.headers(withhost) are as over HTTP/1.1, and so are the responses. Event streams send each event as it comes. - WebSockets stay on HTTP/1.1: a browser opens a separate connection for them, as with most servers.
- A connection with no requests for a minute is closed (with
limit, after a second).
Errors
When a handler (or middleware) raises an error that nothing catches, the request gets the response of on_error — by default 500 Internal Server Error, without the error’s message, so that nothing about the program leaks to the client. The error is written to stderr with the request, and the server goes on:
GET /boom: error 2: index 3 out of range (length 0)A server that can’t start raises error 14: cannot listen on port 80: permission denied, or ... the port is in use.
Details
- Many connections at once, one handler running at a time. Each connection gets its own coroutine: while a handler waits on the network (reading the request, sending the answer, a database query, an
http(...)call), the server answers the others, up to 512 connections at once. Only one handler’s code runs at any moment, so handlers can share the program’s variables without locks; but a variable can change while a handler waits. Read it again after a query, or change it in one go between two waits. A handler that computes for a long time holds the others; for heavy computing, run several servers behind a proxy. - Several servers in one program run side by side with
waitorspawn:wait([api, admin], run)wherefn run(s: http.server)callss.start(). Withlimit, eachstartreturns when its own connections are done, whatever the others do. Work a handlerspawns may go on after that; the program waits for it before it ends. - Connections stay open. A client can send its next request on the same connection (HTTP/1.1 keep-alive), until it says
Connection: close, is quiet for 5 seconds, or sent 100. Withlimit(for tests), each connection answers one request. - Deep calls in a handler. A handler can nest 2,000 calls (the main program 10,000); more raises error 10, as deep recursion does anywhere.
httpsis TLS 1.3 only, without resumed sessions: browsers and current clients all speak it. A failed connection gives its memory back like a finished one.- A request has 30 seconds to arrive; bodies can have a
Content-Lengthor come in chunks, up tomax_body. printin a handler writes to the program’s output at once, also inluma run.- It is written in Luma, on top of
tcpand function values.
Not available yet
- Running handlers on several processor cores.
- WebSocket subprotocols chosen by the server (read
sec-websocket-protocolinreq.headersyourself). - Sessions kept in a database or shared between server processes.
- Uploads written to disk as they come (for files larger than memory), and sending multipart forms from the HTTP client.
- Ranges (resumed downloads, seeking in video) and caching headers (
ETag,Last-Modified) forhttp.file.