Routes and serving

A route: block is an HTTP endpoint. A file with at least one route needs listen in its permissions, and midad run file.md starts a server instead of exiting.

A route

---
midad: "0.1"
module: app
permissions:
  listen: ["127.0.0.1:8787"]
---

```route:GET /notes/:id
const id = get(get(req, "params"), "id");
return respond(200, {"id": id});
```

The fence tag is route:METHOD /path. The methods are GET, POST, PUT, PATCH and DELETE. A path segment that starts with : captures that segment into req.params under its name, and a trailing * captures the rest of the path under the key "*".

A route body must return a response. A body that can fall off its end is E0210, not an empty 200.

The request map

req is in scope in every route body and every before block:

key value
method "GET", "POST", …
path the path, without the query string
params the :name captures and the "*" rest
query the query string, decoded; a repeated name keeps the last value
headers the request headers, lowercased
body the parsed body: a map for JSON or a form, otherwise None
ctx an empty map that before blocks fill with what they declared

A JSON body is parsed when the content type says JSON. A body with application/x-www-form-urlencoded is parsed as a map of strings, which is what an HTML form sends. Anything else stays in body as text.

Responding

respond(status, body) answers JSON: a map or a list is serialized, a string is serialized as a JSON string. respond(status, body, headers) adds response headers, whose values must be strings. respond_html(status, body) sends the body as text/html; charset=utf-8 instead.

The status must be a number from 100 to 599. Every response also carries x-content-type-options: nosniff, referrer-policy: no-referrer and a content-security-policy header; the server sets those itself.

State, and what a request may share

A state block lives for the life of the process. The server runs one interpreter instance per core, each behind its own lock, and a request that finds every instance busy gets a 503. A program with a state block runs a single instance, because there would be no shared answer otherwise. Set MIDAD_WORKERS to override the pool size; MIDAD_WORKERS=1 turns it off.

before: middleware

A before block runs on every matched request, in source order, in the scope the route body then runs in. What it declares with let is visible to the route, and a return respond(...) in it answers the request and the route never runs. A path no route matches never runs middleware.

When a route is answered by a named handler, the handler receives only the request, so it reads middleware state through req.ctx:

const user = get(get(req, "ctx"), "user");

HTML templates

html:NAME is a template. Indentation is the nesting, {{ expr }} inserts a value with HTML escaping on, and {{! expr }} inserts it raw. html("NAME") renders it, and html("NAME", {"k": v}) binds the names its holes read.

```html:page
doctype html
html
  head
    title {{ title }}
  body
    h1 {{ title }}
    ul
      for n in notes
        li {{ n }}
```

if/else and for name in list work inside a template, over the lines indented under them, and the condition must be a boolean. There are no partials, no filters and no whitespace control: nested elements come out on one line, and the bytes are exactly what you wrote.

A hole the map does not bind is E0241 when the map is written out at the call site; pass a map held in a variable and the holes go unchecked.

Handler routes

A route can name a function instead of carrying a body:

```route:GET /links/:id show
```

with function show(req: map): map declared in the same program. That is how a library offers a route the entry file mounts. The function must take one map and return a map (E0257), and on a native C build it compiles to an exported function the server can call.

What the server does with an unmatched request

situation answer
no route matches the path 404 with {"error":"not found"}
a route matches the path but not the method 405 with {"error":"method not allowed"}
HEAD, and a GET route matches the GET route runs and the body is dropped
HEAD, and the program declares its own HEAD route that route runs
no route matched, and static: names a directory the file is served from it

static: in the frontmatter serves a directory for every path no route matched. A path that escapes the directory with .., a symlink out of the tree or a missing file all fall through to the 404.

A whole server, checked

The program below is the one this page was built with: state, a template, middleware, three routes. The requests under it were sent to the running server and the answers are what came back.

serve-1.md
---
midad: "0.1"
module: notes
permissions:
  listen: ["127.0.0.1:18790"]
---

# notes

```state
notes: list = [];
```

```html:page
doctype html
html
  head
    title {{ title }}
  body
    h1 {{ title }}
    ul
      for n in notes
        li {{ n }}
```

```before
let user = unwrap_or(get(get(req, "headers"), "x-user"), "anon");
```

```route:GET /
return respond_html(200, html("page", {"title": "Notes", "notes": notes}));
```

```route:POST /notes
push(notes, str(unwrap_or(get(get(req, "body"), "title"), "untitled")));
return respond(201, {"count": len(notes)}, {"x-seen-by": user});
```

```route:GET /notes/:index
const i = int(get(get(req, "params"), "index"));
if (i < 0 || i >= len(notes)) {
  return respond(404, {"error": "no such note"});
}
return respond(200, {"title": at(notes, i), "user": user});
```
requests and responses
POST /notes -> 201 {"count":1}
POST /notes -> 201 {"count":2}
GET / -> 200 <!doctype html><html><head><title>Notes</title></head><body><h1>Notes</h1><ul><li>buy ink</li><li>read Dune</li></ul></body></html>
GET /notes/1 -> 200 {"title":"read Dune","user":"anon"}
GET /notes/9 -> 404 {"error":"no such note"}
GET /notes -> 405 {"error":"method not allowed"}
On this page