Korr

Full-stack web with Korr

Docs index

Korr ships an HTTP/1.1 server, router, templates, JSON, cookies and a request simulator. No framework, no packages.

Hello web

let app = http.app()
app.get("/", fn(req) => "<h1>Hello from Korr</h1>")
app.listen(8080)
korr server.krr
# Korr server listening on http://127.0.0.1:8080  (press Ctrl+C to stop)

app.listen(port) binds to 127.0.0.1 (only your machine). Use app.listen(port, "0.0.0.0") to accept connections from the network.

Workers: many requests at once

By default the server handles one request at a time. With workers it handles several at once, so a slow request (a big query, a call to another API) no longer makes everyone else wait:

let app = http.app()
app.listen(8080, { workers: 4 })                     // 4 requests at a time
app.listen(8080, { host: "0.0.0.0", workers: "auto" }) // one worker per CPU thread

Or without changing the code: KORR_WORKERS=4 korr server.krr ("auto" works there too).

How it works, and what it means for your program:

Measured on a laptop with bench/http/run.sh (a JSON endpoint doing a little work, 32 concurrent clients): 9,000 requests per second with 1 worker, 18,200 with 2, 30,400 with 4, 38,700 with 8.

Routes

let app = http.app()
app.get("/users/:id", fn(req) => { id: req.params.id })        // /users/42
app.get("/files/*", fn(req) => req.params["*"])                // /files/a/b.txt gives "a/b.txt"
app.post("/users", create_user)
app.put("/users/:id", update_user)
app.delete("/users/:id", fn(req) => null)                      // 204 No Content
app.any("/health", fn(req) => "ok")                            // every method

fn create_user(req) => http.json({ created: true }, 201)
fn update_user(req) => { updated: req.params.id }

The request

A handler receives one argument, req, a map with:

Field Example
req.method "GET"
req.path "/users/42" (URL-decoded)
req.params { id: "42" } from :id / *
req.query { page: "2" } from ?page=2
req.headers lower-case names: req.headers["user-agent"]
req.cookies { sid: "..." }
req.body raw body text
req.json parsed body when Content-Type: application/json (else null)
req.form fields of an HTML form post (urlencoded or multipart/form-data)
req.files uploaded files by field name (see File uploads)
req.session the session map, when app.sessions is on (see Sessions)
req.csrf_token, req.csrf_field the CSRF token, and a hidden <input> with it for forms
req.ip client address

Path and query values are always strings; convert explicitly: int(req.query.page, 1).

Responses

What a handler returns decides the response:

Return value Response
a str or html 200, text/html
a map, array or struct instance 200, JSON
null 204 No Content
http.json(data, status) JSON with a status
http.html(body, status) / http.text(body, status) HTML / plain text
http.redirect(url) 302 redirect
http.response(body, status, headers) anything custom
fn show(req)
    let user = find_user(int(req.params.id, 0))
    if user == null
        return http.json({ error: "user not found" }, 404)
    return user

fn find_user(id) => id == 1 ? { id: 1, name: "Ana" } : null

Headers: pass a map as the last argument , http.text("hi", 200, { "cache-control": "no-store" }). A header value that is an array sends the header several times (useful for multiple set-cookie).

Templates

html"..." strings escape every interpolated value, so user input can never inject markup or scripts. Triple quotes make full pages readable:

fn layout(title, body)
    return html"""
        <!doctype html>
        <html>
        <head><meta charset="utf-8"><title>{title}</title></head>
        <body>{body}</body>
        </html>
        """

fn product_list(products)
    let rows = [html"<li>{p.name}, Rp{p.price}</li>" for p in products]
    return layout("Products", html"<ul>{rows}</ul>")

Validation

validate(data, rules) checks input and converts form strings to real types. It returns { ok, errors, data }; data holds only the fields you listed, so extra fields a client sends (is_admin=true) never reach your database.

fn signup(req)
    let v = validate(req.json ?? req.form, {
        email: "email max:254",
        password: "str min:8 max:200",
        age: "int min:13 max:150 optional",
        plan: "in:free,pro default:free",
        newsletter: "bool",
    })
    if not v.ok
        return http.json({ errors: v.errors }, 422)
    let hash = crypto.hash_password(v.data.password)
    // save v.data.email, hash, v.data.plan ...
    return http.json({ ok: true }, 201)
Rule Meaning
str (default), int, float, bool, email, url, date, array, map, any the type; strings from forms are converted ("34" becomes 34, "on" becomes true)
optional the field may be missing or empty (gives null)
default:VALUE value when missing (implies optional)
min:N, max:N length for strings and arrays, value for numbers
in:a,b,c one of the listed values
raw keep spaces around strings (trimmed otherwise)

Fields are required unless marked optional or given a default. A missing bool is false (an unchecked checkbox sends nothing). Error messages are short phrases for the field: { email: "must be a valid email address", age: "must be at least 13" }. A misspelled rule ("strng") raises a TypeError at once.

File uploads

Forms with enctype="multipart/form-data" put their files in req.files and the other fields in req.form:

// no-check
fn upload(req)
    let f = req.files.avatar
    if f == null
        return http.json({ error: "choose a file" }, 422)
    if f.size > 2_000_000 or not f.content_type.starts_with("image/")
        return http.json({ error: "images up to 2 MB" }, 422)
    let name = "{crypto.uuid()}-{f.filename}"
    f.save("{__dir__}/uploads/{name}")
    return { saved: name }

In tests: app.request("POST", "/upload", { files: { avatar: { filename: "a.png", content_type: "image/png", content: "..." } } }).

Sessions and CSRF protection

Turn sessions on once, with a long random secret from the environment:

// no-check
let app = http.app()
app.sessions(os.env("SESSION_SECRET"), { secure: true })   // secure: HTTPS only

app.post("/login", fn(req)
    let user = check_password(req.form.email, req.form.password)
    if user == null
        return http.redirect("/login?failed=1")
    req.session.user_id = user.id
    return http.redirect("/dashboard"))

app.get("/dashboard", fn(req) => req.session.user_id == null ? http.redirect("/login") : views.dashboard(req))

app.post("/logout", fn(req)
    req.session.clear()
    return http.redirect("/"))

CSRF protection is on with sessions. Every POST, PUT, PATCH and DELETE that is not JSON must carry the session’s token, or Korr answers 403. Put req.csrf_field in every form:

// no-check
fn login_form(req) => html"""
<form method="post" action="/login">
    {req.csrf_field}
    <input name="email"> <input name="password" type="password">
    <button>Log in</button>
</form>"""

JavaScript can send the token in an x-csrf-token header instead (req.csrf_token). JSON requests do not need it: browsers cannot send JSON to another site without its permission. Turn the check off with app.sessions(secret, { csrf: false }) only for apps that have no forms.

Without app.sessions, cookies are still available: req.cookies to read, http.cookie(name, value, options) to build a Set-Cookie header (defaults HttpOnly, SameSite=Lax).

WebSockets

A WebSocket is a connection that stays open, so the server can send messages whenever it wants: chats, live dashboards, notifications, games.

let app = http.app()
app.ws("/chat", {
    open: fn(ws)
        ws.subscribe("room")
        ws.send("welcome, you are number {ws.id}")
    ,
    message: fn(ws, text)
        http.publish("room", { from: ws.id, text: text })   // to everyone in the room
    ,
    close: fn(ws) => print("{ws.id} left"),
})
app.static("/", "public")
app.listen(8080, { workers: 4 })

In the browser:

<script>
  const ws = new WebSocket(`ws://${location.host}/chat`);
  ws.onmessage = (e) => console.log(JSON.parse(e.data));
  ws.onopen = () => ws.send("hello");
</script>

Safe by default:

Each connection belongs to one worker, the one that accepted it; its handlers always run there. Each open connection also uses a small thread for reading.

Server-Sent Events

Server-Sent Events (SSE) are a simpler one-way stream from the server to the browser, over plain HTTP: ideal for notifications, progress and live feeds.

let app = http.app()
app.get("/events", fn(req) => http.sse("news"))            // or http.sse(["news", "alerts"])
app.post("/news", fn(req)
    http.publish("news", req.json.title, "headline")         // optional event name
    return { ok: true }
)
<script>
  const events = new EventSource("/events");
  events.addEventListener("headline", (e) => console.log(e.data));
</script>

http.publish reaches SSE streams and WebSockets alike. The browser reconnects by itself when the stream is interrupted. Behind Nginx, SSE works as is (Korr sends X-Accel-Buffering: no); keep proxy_read_timeout above 15 seconds (the server sends a comment every 15 seconds to keep the stream open).

CORS

Browsers stop a page on one site from reading responses from another site unless that site allows it. To let your frontend at https://app.example.com call an API served by Korr on another domain:

let app = http.app()
app.cors({ origins: ["https://app.example.com"] })
app.cors({ origins: ["https://app.example.com"], credentials: true })   // with cookies
app.cors({ origins: ["*"] })                                            // a public API, no cookies

Korr answers the browser’s preflight requests (OPTIONS) and adds the Access-Control-* headers to responses for allowed sites; other sites get no CORS headers, so the browser keeps their pages from reading your responses. Options: methods (default GET, POST, PUT, PATCH, DELETE), headers the page may send (default content-type, authorization, x-csrf-token), expose (response headers the page may read), max_age (how long the browser may remember the answer, default 600 seconds). credentials: true (cookies) cannot be combined with "*": that would let every website act as your logged-in users.

Rate limiting

let app = http.app()
app.rate_limit({ requests: 100, per: 60 })                          // 100 a minute per client
app.rate_limit({ requests: 5, per: 60, paths: ["/login", "/api/reset"] })   // only these paths

Each client address may make requests requests every per seconds (a token bucket: short bursts up to the limit are fine). Further requests get 429 Too Many Requests with a Retry-After header and never reach your code. The limit is counted once for the whole server, whatever the number of workers. It applies to the real server, not to app.request in tests.

Behind a reverse proxy every request comes from the proxy’s address, so tell Korr to read the client’s address from the proxy’s X-Forwarded-For header:

let app = http.app()
app.trust_proxy(true)     // only when a proxy is in front: the header could be forged otherwise

This also sets req.ip to the client’s address. Korr takes the last address in the header, the one your proxy added.

Middleware with before

let app = http.app()
app.before(fn(req) => req.path.starts_with("/admin") and req.cookies.role != "admin" ? http.text("forbidden", 403) : null)

Every before hook runs in order; returning anything other than null ends the request with that response.

Static files

let app = http.app()
app.static("/public", "{__dir__}/public")    // /public/style.css gives ./public/style.css

Static serving refuses .., encoded traversal, backslashes and hidden files such as .env, and resolves symlinks to make sure the file is inside the folder. Directories serve their index.html.

Errors in handlers

If a handler throws, the client receives a generic 500 Internal Server Error page and the full error (kind, message, line, call trace) is printed on the server’s stderr. Set KORR_DEBUG=1 to include the message in the response while developing.

Testing without a network

app.request(method, path, options?) runs the whole pipeline (hooks, routing, static files, error handling) and returns { status, headers, body }:

// no-check
import "./main.krr" as main

fn test_signup_requires_email()
    let res = main.create_app().request("POST", "/signup", { json: { email: "x", password: "12345678" } })
    assert_eq(res.status, 422)

Run korr test. See CLI.

Databases and calling other APIs

Store data with the built-in db module (SQLite, PostgreSQL, MySQL/MariaDB) and call external services with the HTTP client:

// no-check
const conn = db.open(os.env("DATABASE_URL", "sqlite:app.db"))
app.get("/weather/:city", fn(req)
    let res = http.get("https://api.example.com/weather", { query: { city: req.params.city } })
    if not res.ok
        return http.json({ error: "weather service unavailable" }, 502)
    conn.exec("INSERT INTO lookups (city) VALUES (?)", [req.params.city])
    return res.json
)

Project layout

korr new myapp creates:

myapp/
    main.krr        # create_app() + routes; starts the server when run directly
    views.krr       # html templates
    app_test.krr    # tests with app.request()
    public/
        style.css

The if os.is_main() guard at the bottom of main.krr lets tests import the app without starting the server.

Deployment

korr build main.krr -o myapp        # one executable with all your modules

Copy it to the server with the public/ folder next to it, run it as a service and put a reverse proxy in front for HTTPS (Caddy or Nginx), with workers for concurrent requests. Step by step (systemd, launchd, Windows services, Caddy, Nginx, scaling, Docker, logs and a checklist) in Deployment.


Previous: Standard library Docs index Next: Databases