Skip to content
Jennifer Programming Language

web - a small HTTP framework

import "web.j" as web;

An ergonomic HTTP framework over the httpd server engine. Register routes against handler func values, then web.run owns the accept loop, matches each request, and dispatches to the handler - so a web app reads as a set of handlers plus a route table, not a hand-written server loop.

Needs the default jennifer binary (the httpd engine is net-backed; the constrained jennifer-tiny has no network stack).

Concurrency: requests are handled concurrently

The serve loop handles requests concurrently: it accepts a request, hands it to its own spawned worker, and immediately accepts the next. A handler that blocks - a sql query, an outbound http / rest call, memcache, a slow file read - does not stall the requests behind it; each runs on its own worker. In-flight concurrency is bounded by the httpd engine's in-flight limit.

Dispatch calls each handler func value, which runs in its home (entry-program) context; that cross-boundary call path is race-safe: each worker carries its own call-depth counter, and reads of shared program state (top-level constants, variables, and the maps / lists they hold) are safe to do from many handlers at once.

The one thing that is not safe by construction is a handler writing a shared top-level variable of the entry program. Unlike a top-level spawn (which deep-copies the scope it captures, so a data race is impossible), handler workers run against the same entry-program globals - so two handlers that mutate one top-level def at overlapping times race on it, like threads sharing memory. Keep per-request mutable state where it belongs:

  • In the request / response. The web.Context and its helpers are per-request.
  • In a synchronized store, not a bare global a handler assigns. Server-side session state goes through the session module; a counter or cache that several handlers update needs its own synchronization, not a top-level def.
  • Offload slow, response-independent work (sending mail, writing an audit log) to a spawn the handler does not wait on.

Sharing a large parsed document

A document every request reads - a flatdb store, a parsed JSON / YAML / TOML file - belongs in a top-level def, loaded once at startup. Handlers read it concurrently, and reading it costs no copy: a json.Value (and every opaque library value) is immutable, so binding it, passing it to a handler, or capturing it in a spawn shares the one parsed tree. Parsing it again in each handler instead multiplies its in-memory size (from about its file size for text-heavy documents up to roughly 15 times it for one made of many small values) by the number of requests in flight.

jennifer
import "flatdb.j" as flatdb;
import "web.j" as web;

def store as flatdb.DB init flatdb.open("registry.json");   # parsed once

func listDecks(ctx as web.Context) {
    web.sendJson($ctx, 200, flatdb.get($store, "/decks"));   # shared, not copied
}

When the document changes while the server runs, a top-level def cannot be reassigned safely from concurrent handlers. Publish each new version through a kv store instead: kv.setValue($cache, "registry", $db.data, 0) replaces the shared value atomically, and kv.getValue($cache, "registry") hands each request the current one, again without copying the tree. See kv values.

Shutdown and handler lifecycle

Per-request workers have two consequences:

  • Shutdown does not drain in-flight workers. httpd.shutdown (from another task or a signal handler) stops the accept loop; workers already running are not waited on. Their clients still get a clean 503 (the engine unblocks them), but a handler mid-way through response-independent work (a started write, an outbound call) is abandoned when the process exits. If you need in-flight requests to finish, quiesce the load before shutting down.
  • exit from a handler does not stop the server. Each worker is task.discarded, and discard suppresses a task's exit (standard task semantics), so exit / exit N called inside a handler is inert - one request cannot unilaterally terminate a multi-request server. Stop the server with httpd.shutdown (optionally from an os.catchSignal handler), not exit.

Handlers

A handler is a top-level function taking a web.Context:

jennifer
import "web.j" as web;

func showUser(ctx as web.Context) {
    web.text($ctx, 200, "user " + web.param($ctx, "id"));
}

def app as web.App init web.new();
$app = web.get($app, "/users/:id", showUser);
web.run($app, ":8080");

A route stores the handler as a func value (pass a function by its bare name, web.get($app, "/x", showUser)). A func value carries its home interpreter, so a handler defined in the entry program is called back in the entry program's context across the module boundary - it resolves its own imports and can build the app's own structs. A bare name that is not a defined function is a parse-time error at the call site, so a mistyped handler fails before the server ever starts.

The web.Context

Everything a handler needs hangs off the web.Context it receives, so it rarely touches httpd directly:

CallReturns
web.method($ctx)stringRequest method.
web.path($ctx)stringRequest path.
web.param($ctx, name)stringA captured :param ("" if none).
web.query($ctx, name)stringA query-string parameter.
web.rawQuery($ctx)stringThe whole query string as sent, no ? ("" if none): still encoded, repeats and order kept. For a redirect that must keep the query.
web.header($ctx, name)stringA request header.
web.body($ctx)bytesThe raw request body (binary-safe).
web.bodyJson($ctx)json.ValueThe request body decoded as JSON.
web.form($ctx)map of string to stringThe x-www-form-urlencoded body, decoded.
web.formValue($ctx, name)stringOne form field ("" if absent).
web.multipartForm($ctx)list of multipart.PartThe multipart/form-data body (file uploads), parsed via the multipart module. Import multipart.j in the handler to name multipart.Part / use multipart.isFile / multipart.text.
web.remoteAddr($ctx)stringThe client's host:port.
web.remoteHost($ctx)stringThe client's host without the port (2001:db8::1 for [2001:db8::1]:5000). Key per-client state on this: the port changes with every connection. Behind a reverse proxy it is the proxy.
web.setHeader($ctx, name, value)nullSet a response header (before responding).
web.respond($ctx, status, body)nullSend a response (body is a string).
web.text($ctx, status, body)nullRespond with text/plain.
web.html($ctx, status, body)nullRespond with text/html.
web.sendJson($ctx, status, doc)nullRespond with application/json from a json.Value.
web.sendGzip($ctx, status, body)nullRespond, gzip-compressed when the client accepts it.
web.redirect($ctx, status, location)nullRedirect (301/302/303/307/308) with a Location header.
web.serveFile($ctx, path)nullRespond with a file from disk.
web.serveDir($ctx, root)nullServe static files from a directory root (httpd.serveDir: dotfiles, unindexed directories and symlinks out of root are 404).

Cookies

Pure HTTP-header work over httpd, no extra dependency:

CallReturns
web.cookie($ctx, name)stringThe request cookie's value ("" if absent).
web.setCookie($ctx, name, value, opts)nullEmit a Set-Cookie response header.

opts is a web.CookieOptions - path, domain, maxAge (int seconds; 0 omits the attribute, negative expires the cookie now), httpOnly, secure, sameSite ("Lax" / "Strict" / "None" / ""; any other value, including another spelling, throws kind web, and "None" requires secure). A zero-value struct is a plain session cookie. Several setCookie calls emit several Set-Cookie headers (they are not collapsed).

Sessions

web owns only the session id cookie; the session data lives in a store the app owns, so web forces no store or network dependency (it never imports session / memcache). That keeps a web app that uses no sessions at httpd + meta + json + collections.

CallReturns
web.sessionId($ctx, cookieName)stringThe request's session id, minting a new UUID + HttpOnly / SameSite=Lax / path-/ cookie on first use.
web.renewSession($ctx, cookieName)stringRotate the id: mint a fresh UUID and set it as the cookie, returning the new id.

sessionId only accepts an incoming cookie that matches the UUID shape it mints; a malformed or non-UUID value is discarded and a fresh id issued. That check stops an attacker from smuggling metacharacters through the id into a store keyed by it, but it does not by itself stop session fixation - a well-formed UUID an attacker plants (via a sibling subdomain or a stray XSS) still passes. The fixation defence is to rotate the id: after any privilege change - a successful login, a logout, a role change - call web.renewSession and move your session data to the returned id.

Call web.sessionId once per request and pair the id with your own store. The session module (over memcache / redis for multi-process serving) mints its own ids and saves only sessions it created, so with it carry its id in a cookie of your own instead:

jennifer
use json;
use uuid;
import "web.j" as web;
import "session.j" as session;
import "kvstore.j" as kvstore;

def store as kvstore.Store init kvstore.inProcessStore();   # the app's store

func profile(ctx as web.Context) {
    def id as string init web.cookie($ctx, "sid");
    if (not (uuid.isValid($id) and session.exists($store, $id))) {
        $id = session.create($store, 3600);
        def opts as web.CookieOptions;
        $opts.path = "/";
        $opts.httpOnly = true;
        $opts.secure = true;
        $opts.sameSite = "Lax";
        web.setCookie($ctx, "sid", $id, $opts);
    }
    def data as json.Value init session.load($store, $id);
    # ... read / write $data ...
    session.save($store, $id, $data, 3600);   # false: logged out meanwhile
    web.text($ctx, 200, "ok\n");
}

Stateless signed-cookie sessions (data in the cookie, no store) are not provided; an app can build one over hash.hmac / hash.equal.

Registering routes

Each registrar returns a new App (value semantics), so build the app by threading it through:

Call
web.new()An empty app.
web.get($app, pattern, handler)Register a GET route.
web.post / web.put / web.patch / web.deleteThe other verbs.
web.route($app, method, pattern, handler)The general form.
web.mount($app, prefix, $sub)Re-register every route of the sub-router $sub under prefix ("/v1"; "" or "/" = root). Only routes are composed: middleware, the not-found and error handlers, and CORS stay $app's.
web.joinRoute(prefix, pattern)The pattern a mounted route is served under: joins the two with a single leading slash, dropping empty segments ("/v1" + "/deck" -> "/v1/deck", "" + "" -> "/").
web.before($app, handler)Add a middleware (runs before each route handler).
web.notFound($app, handler)A custom handler for unmatched requests (default: a plain 404).
web.onError($app, handler)An error handler for a throwing route / middleware (default: log to stderr).
web.onServerError($app, handler)The same, but not called for a client fault (an error answered 4xx).
web.allocBudget($app, maxBytes)A per-request allocation budget in bytes (see Memory per request); math.MAX_INT removes it, 0 or negative throws a WebError (500).

A HEAD request is served by the matching GET route automatically (HTTP requires it, and health checks / caches rely on it); the response body is suppressed by the server, so the handler needs no special-casing.

Patterns are /-separated. A segment beginning with : captures a single parameter: /users/:id/posts/:pid matches /users/7/posts/9 and captures id = 7, pid = 9. A trailing segment beginning with * is a wildcard that captures the entire remainder (joined by /, possibly empty): /files/*path matches /files/css/app.css with path = css/app.css, and /*path is a catch-all - a natural SPA fallback. Read either with web.param($ctx, name).

The first matching route wins, so register specific routes before a wildcard (a greedy /*path registered first would swallow everything). A wildcard is only special as the last pattern segment. Runs of / in a request path count as one (//a///b is /a/b), and a path of more than 128 segments matches no route, wildcards included, so it is a 404: routing runs before any handler or middleware, and the request line may be as long as the 64 KiB header cap.

jennifer
$app = web.get($app, "/static/*path", serveStatic); # nested static files
$app = web.get($app, "/*page", spaIndex);           # fallback, registered last

Middleware

A middleware is a handler that runs before the route handler and returns a bool: true to continue, or respond and return false to halt (e.g. an auth gate):

jennifer
use encoding;
use os;
use hash;

def const API_KEY as string init os.getEnv("API_KEY");

func requireKey(ctx as web.Context) {
    def given as bytes init encoding.encode("utf-8", web.header($ctx, "X-Api-Key"));
    # hash.equal compares in constant time; == would leak the key's prefix
    # through response timing. An unset key never matches.
    if (not (API_KEY == "") and hash.equal($given, encoding.encode("utf-8", API_KEY))) {
        return true;
    }
    web.text($ctx, 401, "unauthorized\n");
    return false;
}

$app = web.before($app, requireKey);

Every request is answered exactly once: if a handler throws or forgets to respond, the framework sends a 500 so the connection never hangs.

Error handling

When a handler or middleware throws, web contains the error (so one bad request never stops the accept loop) and answers it:

Escaped errorAnswerstderr
web.WebError with a 4xx status (400: a request body that cannot be read)that status, 400 <message>no
web.WebError of kind "limit", status 413 (a body past a parser cap, such as 10000 form fields)413 content too largeno
the same while the request's allocation budget (web.allocBudget) is spent500 internal server errorkind / message
any other kind "limit" (a cap the server hit on its own work: an outbound response, a query result, the allocation budget)500 internal server errorkind / message / position
anything else500 internal server errorkind / message / position

web.WebError{kind: "web", message, status} is every error of kind "web": 400 from the body readers below, 500 for a misconfiguration (an empty CSRF secret, a bad cookie option, CORS credentials with a wildcard origin). The body readers also throw it with kind "limit" and status 413 for a body past their caps, so a catch matching the generic kind still sees "limit". A handler that wants its own answer catches it as usual. Register an error handler to route errors somewhere else (a log file, an alerting service):

jennifer
use io;

func logError(err as Error) {
    io.eprintf("request failed: %s: %s (%s:%d)\n", $err.kind, $err.message, $err.file, $err.line);
}
$app = web.onError($app, logError);

The handler receives the thrown value (the Error struct by convention), every answered status included; it is for observability and cannot change the response. A client can therefore call it once per malformed request; a hook that pages or sends mail is registered with web.onServerError($app, handler) instead, which skips every error answered 4xx (one registration replaces the other). A module's own error struct (web.WebError too, that escapes a route rest.HttpError, smtp.SmtpError, ... - any struct with string kind and message fields) arrives as an Error with that kind and message, so a handler typed as Error sees it too; its extra fields are in the stderr line, and its file / line are empty. Any other thrown value arrives as it is. An error thrown by the error handler itself is caught and logged, never re-raised.

Reading form bodies

web.form($ctx) parses an application/x-www-form-urlencoded body into a map, and web.formValue($ctx, name) reads one field. Both are strict: a % without two hex digits, or a body or value that is not UTF-8, throws a web.WebError with status 400, answered 400 unless the handler catches it. Browsers never send either from a UTF-8 page; a page in another charset makes them send it, so serve forms with charset=utf-8 (web.html does). web.bodyJson (a body that is not UTF-8 or not JSON) and web.multipartForm (a missing boundary, a malformed part) throw the same 400. The split runs in Go (encoding.parseForm), so a hostile &&&... body costs no more than its size; more than 10000 fields throw a web.WebError of kind "limit", status 413, answered 413 (this runs before any route or login check once csrfCheck is middleware, which answers a malformed form body 400). web.cookie reads the Cookie header the same way (encoding.parseCookies). web.csrfCheck only falls back to the csrf form field for an actual urlencoded body - a JSON or multipart request is left to the X-CSRF-Token header.

Authentication

web parses the incoming Authorization header; checking the credentials (against your user store) and sending the 401 challenge stay app code.

CallReturns
web.basicAuth($ctx)BasicCredentialsDecode Authorization: Basic base64(user:pass).
web.bearerToken($ctx)stringThe token from Authorization: Bearer <token> ("" if absent).

BasicCredentials is { user, password, present }; present is false when the header was missing or malformed. A Basic-auth gate is a middleware:

jennifer
func requireLogin(ctx as web.Context) {
    def cred as web.BasicCredentials init web.basicAuth($ctx);
    if ($cred.present and checkUser($cred.user, $cred.password)) {
        return true;
    }
    web.setHeader($ctx, "WWW-Authenticate", "Basic realm=\"app\"");   # the 401 challenge is a two-liner
    web.text($ctx, 401, "unauthorized\n");
    return false;
}
$app = web.before($app, requireLogin);

For bearer tokens, web.bearerToken($ctx) extracts the token; validate it yourself (an opaque lookup, or jwt.verify). Client-side auth (sending Authorization) lives in the rest module (rest.basic / rest.bearer). Digest auth is not supported (a legacy, challenge/nonce scheme; use Basic over TLS or a bearer token).

CSRF

Stateless, HMAC-signed double-submit tokens. web holds no secret or session state - the app supplies a secret (a stable per-deployment string) and opts in with a middleware. A token is <random>.<hmac(secret, random)>, minted into the CSRF cookie and echoed by the client; a request is accepted only when the submitted token equals the cookie and its signature verifies, so a forger without the secret cannot mint one. An empty secret throws a web.WebError with status 500, because with "" as the key anyone could mint a token.

A token is not bound to a client or session: any token the app minted is valid. What keeps an attacker from planting their own token in a victim's browser is the cookie's name. With Secure cookies (the default) it is __Host-csrf, which a browser accepts only from an HTTPS origin, with Path=/ and without Domain - so neither a sibling subdomain nor a man in the middle on plaintext HTTP can set it. Under JENNIFER_WEB_INSECURE_COOKIES=1 the prefix is not allowed, and the cookie is plain csrf: that mode is for plaintext-HTTP development only. (Chrome and Firefox treat http://localhost as secure and accept __Host- cookies there; Safari does not, so develop with JENNIFER_WEB_INSECURE_COOKIES=1 when you test in Safari over plain HTTP.)

CallReturns
web.csrfToken($ctx, secret)stringMint a token, set the __Host-csrf cookie (csrf in insecure dev mode), return it for the form / an X-CSRF-Token header. Idempotent per request.
web.csrfCheck($ctx, secret)boolTrue when the request carries a valid token.

web.csrfToken is idempotent per request: the token and its cookie are minted on the first call and memoized for the rest of the request, so every call returns the same token. A multi-form page can call web.csrfToken once per form, including in a loop or in page chrome (a header sign-out button): all forms carry one token bound to the one CSRF cookie, so all of them validate. (The cookie holds a single value; a second, different token would replace it and break every form already rendered.)

Mint the token in the GET handler that renders a form; guard the unsafe methods with a middleware:

jennifer
use os;

def const CSRF as string init os.getEnv("CSRF_SECRET");   # a stable secret

func showForm(ctx as web.Context) {
    def token as string init web.csrfToken($ctx, CSRF);
    web.html($ctx, 200, "<form method=post><input type=hidden name=csrf value=" + $token + ">...</form>");
}

func guardCsrf(ctx as web.Context) {
    def m as string init web.method($ctx);
    if ($m == "GET" or $m == "HEAD") {
        return true;                       # safe methods
    }
    if (web.csrfCheck($ctx, CSRF)) {
        return true;
    }
    web.text($ctx, 403, "CSRF check failed\n");
    return false;
}
$app = web.before($app, guardCsrf);

The submitted token is read from the X-CSRF-Token header (for JSON / fetch clients) or the csrf form field (for HTML forms).

CORS

web.cors($app, opts) -> App sets a cross-origin policy for the whole app. When it is set, the serve loop adds the Access-Control-* headers to every response and answers a preflight OPTIONS request with a 204 before routing, so no handler repeats it.

jennifer
def opts as web.CorsOptions;
$opts.allowOrigin = "*";
$opts.allowMethods = "GET, POST, PUT, DELETE, OPTIONS";
$opts.allowHeaders = "Content-Type, Authorization";
$app = web.cors($app, $opts);

opts is a web.CorsOptions - allowOrigin ("*" or a specific origin; "" leaves CORS off), allowMethods, allowHeaders, allowCredentials (bool), and maxAge (int seconds, 0 omits it). A zero-value struct is CORS off, so web.new() starts with no policy.

Caching

Static files are already cached: web.serveFile / web.serveDir ride Go's file server (httpd.serveFile / httpd.serveDir), which sets Last-Modified and answers If-Modified-Since (and Range) on its own. They add a content-hash ETag when the server was opened with httpd.Options{etag: true} (httpd.listenWith). Plain cache headers are a one-liner - web.setHeader($ctx, "Cache-Control", "max-age=3600") - so there is no wrapper for them.

For a dynamic response, web.etag($ctx, tag) -> bool handles the conditional GET: it sets the ETag header and, if the request's If-None-Match matches, answers 304 Not Modified (412 Precondition Failed for a write such as a PUT) and returns true so the handler stops before sending the body. tag is your choice of validator - a content hash (via hash), a database row version, an mtime - so web needs no hashing of its own.

jennifer
func page(ctx as web.Context) {
    def body as string init render();
    def tag as string init hashOf($body); # your validator
    if (web.etag($ctx, $tag)) {
        return;                            # 304 sent; skip the body
    }
    web.text($ctx, 200, $body);
}

The match follows RFC 7232: * matches, the If-None-Match value is parsed as a comma list, and a weak W/ prefix is stripped before comparing (it wraps httpd.etag).

Compression

web.sendGzip($ctx, status, body) answers with the body gzip-compressed when the client's Accept-Encoding names gzip, otherwise plain. It always sets Vary: Accept-Encoding (so caches don't cross the wires) and, when compressing, Content-Encoding: gzip. Set the Content-Type yourself first. Worth it for large text / JSON / HTML; skip it for already-compressed payloads (images, archives).

jennifer
use fs;
use json;
import "web.j" as web;

def report as json.Value init json.decode(fs.readString("report.json"));

func sendReport(ctx as web.Context) {
    web.setHeader($ctx, "Content-Type", "application/json");
    web.sendGzip($ctx, 200, json.encode($report));
}

Serving

Call
web.run($app, addr)Listen on addr and serve forever (blocks; interrupt to stop).
web.serveOn($app, srv)Serve on an already-listening httpd.Server you hold - so you can shut it down (or serve from a spawn). Runs at most httpd.maxInFlight(srv) handlers at once; further requests wait in the engine.

web.run is the common path. Use web.serveOn when you want the server handle, e.g. to shut down from another task, or to open the server with httpd.listenWith and its httpd.Options (body cap, in-flight limit, respond timeout):

jennifer
use httpd;
use task;

def srv as httpd.Server init httpd.listen(":8080");
def worker as task of null init spawn { web.serveOn($app, $srv); };
# ... later ...
httpd.shutdown($srv);
task.wait($worker);

Memory per request

web.allocBudget($app, maxBytes) gives every request an allocation budget: the worker task that handles it calls task.setAllocBudget(limit) before routing, so the middleware, the handler, the module code they call and the tasks they spawn count the bytes they allocate against it (see the task library). A request that builds a value past the budget raises a catchable Error{kind: "limit"} in its handler instead of running the process out of memory; one that escapes is answered 500 and written to stderr, and every other request goes on.

jennifer
use math;

$app = web.allocBudget($app, 64 * 1024 * 1024);   # 64 MiB per request

The answer is 500, not the 413 of a parser cap: the request may be small, it is the server that declines to spend more on it, and retrying it trips again (a 503 would invite clients and proxies to retry). The count is cumulative (allocated, not live: building a string by + in a loop counts every intermediate string), so size the budget from task.allocatedBytes() logged by a representative request, with headroom.

Slow handlers and the respond timeout

The httpd engine answers a request 503 itself when the handler has not answered within the server's respond timeout (60 s by default; see the respond timeout). A handler that legitimately runs longer needs a server opened with a larger respondTimeoutMs, served with web.serveOn:

jennifer
use httpd;

def srv as httpd.Server init httpd.listenWith(":8080",
    httpd.Options{respondTimeoutMs: 5 * 60 * 1000});   # other fields 0: defaults
web.serveOn($app, $srv);

A handler that overruns anyway can no longer answer. web.isOpen($ctx) returns false once the request has been answered, so a long handler can check it before doing work whose reply has nowhere to go. If the handler still tries to reply, web notes it in one stderr line (the client already got 503, so its reply was dropped) instead of reporting a handler error, and does not call the onError hook: nothing failed, the reply was too late. Any other error the handler throws after the timeout is still a handler failure, reported on stderr and to onError as usual.

Call
web.isOpen($ctx)bool: true while a reply can still be sent; false once answered (by the handler, or by the server after the respond timeout).

Running with jennifer serve

jennifer serve app.j runs a web app; --watch restarts it whenever the entry file changes - a Hugo-style edit / reload loop:

sh
jennifer serve app.j            # run the app
jennifer serve app.j --watch    # reload on change

--watch is not web-specific: it re-runs any program on every change to the entry file, so it doubles as an autorun / edit-and-rerun loop for plain scripts too. See the serve command.

See also

  • httpd - the server engine web is built on.
  • http - the HTTP client module (talk to other servers).
  • json - encode response bodies for web.sendJson.
  • rest, session, ratelimit - companions for a fuller serving stack.

Academy talks

TalkWhat it shows
A production web API in Jenniferthe app, context and middleware beneath webapi
A web app in Jennifer from scratchroutes, middleware, forms, CSRF tokens and a clean stop
Errors done right in Jenniferweb.onError handing every caught error over as Error
From PHP to Jennifera long-running web server instead of a request per script
Jennifer facing hostile inputwhat the web module enforces at the request boundary
Your own MCP server in JenniferStreamable HTTP endpoint with a bearer token

API reference

Every exported function, struct and constant of web, with its signature, generated from the module's doc comments: the web API reference.