writeonce/docs/examples/porch/router/router.wo
shoney.arickathil ffd791d05b refactor(porch): name the web framework porch, fix the wo.toml identifier claim
- docs/examples/writeonce-serve -> docs/examples/porch (git mv, history kept);
  `[deps]` key and import are now `porch` / `porch/http` / `porch/router`
- name history preserved on the library README, not rewritten into dated
  records: writeonce-framework -> writeonce-serve (08-25) -> porch (08-26).
  Stories, specs, plans and the audit reports keep the older name by the
  repo's own convention; only live docs and every path link were rewritten
- left alone deliberately: `internal/serve.wo`, `pub fn serve`, `serve_conn`,
  `app.serve(...)` — those are functions, not the module name
- web-app/wo.toml comment corrected: it claimed hyphens are not identifier
  characters and named a key this file never used. lexer.ml's `is_ident_cont`
  DOES accept `-` (an internal dash is part of the identifier, which is why
  binary minus needs spaces), so a hyphenated key would be legal too
- site now teaches the name: package card, the two-deps chapter and the
  handlers-are-classes chapter say `porch`; site-accept asserted the old
  /packages/serve route and caught the rename, as a gate should
- gates: web-app 46/0, site 21/0, deps-accept 8/0, oop-e2e 116/0,
  linkcheck 0 broken / 0 anchors; porch typechecks entry-less as kind=library

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-26 19:36:34 +02:00

146 lines
4.9 KiB
Text

-- router/router.wo — the handler model and the route table.
--
-- No function values in this language, by doctrine — so a handler is a
-- CLASS satisfying the Handler interface (its fields are the closure
-- substitute), dispatched structurally (ICALL). A class missing `handle`
-- is a compile error (WO-E205). Middleware is its own interface because
-- the signature differs: `before` returns `?Resp` — nil means continue,
-- a Resp short-circuits (401 gates, redirects).
pub interface Handler {
fn handle(req: Req) -> Resp
}
-- `mut req`: middleware may WRITE the request — auth attaches the
-- authenticated principal (req.principal) for downstream handlers.
pub interface Middleware {
fn before(mut req: Req) -> ?Resp
}
-- framework v1 slice 2: the response half of the chain. `after` runs on
-- EVERY response leaving dispatch — handler answers, middleware
-- short-circuits, the framework 404/405 — so security headers and CORS
-- reach all of them. It mutates, never replaces (no ?Resp: an after that
-- could swallow the response would be a second handler).
pub interface After {
fn after(req: Req, mut r: Resp)
}
-- Wrapper record, same reason as Mw/Route.
pub class Aw {
a: After
}
-- One route: method + pattern + the handler value. Built with a ctor
-- literal at the registration site (`Route { method: "GET", pattern:
-- "/products/:id", h: ProductShow {} }`) — the exact ownership shape the
-- conformance corpus pins (run/container-owned-move).
pub class Route {
method: Text
pattern: Text
h: Handler
}
-- Middleware wrapper record, same shape as Route for the same reason.
pub class Mw {
m: Middleware
}
-- Request-line logging, the one middleware every framework ships: method +
-- path to stderr, never short-circuits. A stateless handler declares NO
-- fields and constructs as `Logging {}` — an earlier convention gave every
-- one of them a filler `pad: Int`, which the language never required.
pub class Logging {
fn before(mut req: Req) -> ?Resp {
print_err("${req.method} ${req.path}");
return nil;
}
}
-- Does `pattern` match `path`? Fills `params` with :name captures.
-- Segments split on '/', empties dropped (so "/a//b" == "/a/b" and the
-- root "/" is the empty segment list). First mismatch wins; a :segment
-- captures anything non-empty. A LAST segment `*name` (framework v1
-- slice 2) captures the whole rest — zero or more segments, re-joined
-- with '/' — so "/files/*path" matches "/files" (path = "") and
-- "/files/a/b" (path = "a/b"). A `*` anywhere else never matches:
-- precedence stays registration order, wildcards last by construction.
pub fn route_match(pattern: Text, path: Text, mut params: map<Text, Text>) -> Bool {
let ps = split(pattern, "/");
let xs = split(path, "/");
let psegs: multi Text = [];
for s in ps { if s != "" { push(psegs, s); } }
let xsegs: multi Text = [];
for s in xs { if s != "" { push(xsegs, s); } }
let np = len(psegs);
let wild = false;
if np > 0 {
if starts_with(psegs[np - 1], "*") { wild = true; }
}
if wild == false {
if np != len(xsegs) { return false; }
} else {
if len(xsegs) < np - 1 { return false; }
}
let i = 0;
while i < np {
let p = psegs[i];
if wild and i == np - 1 {
let rest = "";
let j = i;
while j < len(xsegs) {
if rest == "" { rest = xsegs[j]; } else { rest = "${rest}/${xsegs[j]}"; }
j = j + 1;
}
params[substr(p, 1, len(p) - 1)] = rest;
return true;
}
if starts_with(p, "*") { return false; }
let x = xsegs[i];
if starts_with(p, ":") {
params[substr(p, 1, len(p) - 1)] = x;
} else {
if p != x { return false; }
}
i = i + 1;
}
return true;
}
-- framework v1 slice 2: a route GROUP — a prefix plus its own routes and
-- its own before-middleware, mounted into an App in one move. The group
-- prefixes patterns at REGISTRATION (the mount is a plain move); its
-- middleware becomes prefix-scoped on the App: it runs only for paths
-- under the prefix, after the global chain, before the route scan.
pub class Group {
prefix: Text
routes: multi Route = []
middleware: multi Mw = []
fn get(pattern: Text, take h: Handler) {
push(self.routes, Route { method: "GET", pattern: "${self.prefix}${pattern}", h: h });
}
fn post(pattern: Text, take h: Handler) {
push(self.routes, Route { method: "POST", pattern: "${self.prefix}${pattern}", h: h });
}
fn put(pattern: Text, take h: Handler) {
push(self.routes, Route { method: "PUT", pattern: "${self.prefix}${pattern}", h: h });
}
fn delete_(pattern: Text, take h: Handler) {
push(self.routes, Route { method: "DELETE", pattern: "${self.prefix}${pattern}", h: h });
}
fn use_mw(take m: Mw) {
push(self.middleware, m);
}
}
-- A prefix-scoped middleware entry on the App (what mounting a group's
-- middleware becomes).
pub class Gmw {
prefix: Text
m: Middleware
}