module use "std/route.nib"
Route
A route table as a value: match a request's method and path against patterns like /notes/:id, and read query strings and form bodies. Nothing here raises.
Route does the three things every small site otherwise writes by hand: pick a handler by method and path, read the query string, and read a submitted form. A route table is an ordinary Vec<Route.Rule>, built with Route.get and Route.post, and Route.dispatch answers a request with the first rule that matches.
let routes = #[
Route.get("/", { r, ps -> Http.text(200, "home") }),
Route.get("/notes/:id", { r, ps -> Http.text(200, "note {Map.get_or(ps, "id", "")}") }),
Route.post("/notes", { r, ps -> Http.text(201, "saved {Map.get_or(Route.form(r), "title", "")}") })
];
let ask = { m, t, b -> Route.dispatch(routes, Http.Request{ method: m, target: t, version: "HTTP/1.1", headers: #[], body: b },
{ r -> Http.text(404, "nothing at {Route.path(r)}") }) };
Vec.map(#[ask("GET", "/notes/42?x=1", ""), ask("POST", "/notes", "title=Milk+run"), ask("DELETE", "/notes/42", "")],
{ a -> (a.status, a.body) })
#[(200, "note 42"), (201, "saved Milk run"), (404, "nothing at /notes/42")]
Patterns
A pattern is /-separated segments, compared with the request's path (the target without its query string):
/aboutmatches exactly/about./notes/:idmatches/notes/42and binds"id"to"42". The bound value is percent-decoded./static/*matches/static/a/b.cssand binds"*"to"a/b.css". A*takes the rest of the path, so it belongs last.
The bindings reach the handler as its second argument, a Map<String, String>.
Nothing raises
A path, query or form that cannot be read the way a pattern wants simply does not match, and a malformed escape such as %zz is kept as written. A handler built on Route therefore keeps the empty raises row Server.run asks of it.
Data
data Rule where
method :: String;
pattern :: String;
handler :: pin (Http.Request, Map<String, String>) -> Http.Response
One route: an HTTP method, a pattern, and the handler that answers a request matching both. The handler receives the request and the pattern's bindings. Build one with Route.get, Route.post or Route.on.
data Match where Matched(Map<String, String>); NoMatch
The answer of Route.match_path: Matched(bindings) when the path fits the pattern, NoMatch when it does not.
Functions
func on :: method: String, pattern: String, handler: pin (Http.Request, Map<String, String>) -> Http.Response -> Route.Rule
A Route.Rule for any method — Route.on("DELETE", "/notes/:id", h).
let rule = Route.on("PUT", "/notes/:id", { r, ps -> Http.nothing(204) });
(rule.method, rule.pattern)
("PUT", "/notes/:id")
func get :: pattern: String, handler: pin (Http.Request, Map<String, String>) -> Http.Response -> Route.Rule
A Route.Rule for GET requests to pattern.
func post :: pattern: String, handler: pin (Http.Request, Map<String, String>) -> Http.Response -> Route.Rule
A Route.Rule for POST requests to pattern.
func dispatch :: routes: Vec<Route.Rule>, r: Http.Request, otherwise: pin (Http.Request) -> Http.Response -> Http.Response
Answers r with the first rule in routes whose method and pattern both match, calling its handler with the request and the pattern's bindings. When no rule matches, otherwise(r) answers — usually a 404, but the choice is yours. Rules are tried in order, so put a specific pattern before a * that would also match.
let routes = #[
Route.get("/files/readme", { r, ps -> Http.text(200, "the readme") }),
Route.get("/files/*", { r, ps -> Http.text(200, "file {Map.get_or(ps, "*", "")}") })
];
let get = { t -> Route.dispatch(routes, Http.Request{ method: "GET", target: t, version: "HTTP/1.1", headers: #[], body: "" },
{ r -> Http.text(404, "not found") }).body };
(get("/files/readme"), get("/files/img/logo.png"), get("/other"))
("the readme", "file img/logo.png", "not found")
func match_path :: pattern: String, path: String -> Route.Match
Whether path fits pattern, and what its :name and * segments bound. Route.dispatch uses it; call it directly to test a pattern.
let show = { m -> match m
Route.Matched(ps) => "matched {Map.size(ps)}: {Map.get_or(ps, "id", "-")}"
Route.NoMatch => "no match"
end };
(show(Route.match_path("/notes/:id", "/notes/hello%20world")), show(Route.match_path("/notes/:id", "/notes")))
("matched 1: hello world", "no match")
func path :: r: Http.Request -> String
The request's target without its query string.
Route.path(Http.Request{ method: "GET", target: "/search?q=nib", version: "HTTP/1.1", headers: #[], body: "" })
/search
func query :: r: Http.Request -> Map<String, String>
The query string as a map, decoded: + is a space and %XX escapes are decoded. A key given twice keeps its last value; a key with no = maps to "". A target with no ? answers an empty map.
let r = Http.Request{ method: "GET", target: "/search?q=nib+lang&page=2", version: "HTTP/1.1", headers: #[], body: "" };
let q = Route.query(r);
(Map.get_or(q, "q", ""), Map.get_or(q, "page", "1"), Map.get_or(q, "missing", "default"))
("nib lang", "2", "default")
func form :: r: Http.Request -> Map<String, String>
The request body read as an application/x-www-form-urlencoded form — what an HTML <form method="post"> sends — decoded the same way as Route.query.
let r = Http.Request{ method: "POST", target: "/sign", version: "HTTP/1.1", headers: #[], body: "name=Bo&msg=hi%21+there" };
let f = Route.form(r);
"{Map.get_or(f, "name", "")} says {Map.get_or(f, "msg", "")}"
Bo says hi! there
func pairs :: s: String -> Map<String, String>
Decodes a key=value&key=value string into a map. Route.query and Route.form are this applied to the query string and the body. An empty part is skipped.
Route.pairs("a=1&b=x%20y&&flag")
{"a": "1", "b": "x y", "flag": ""}
func decode :: s: String -> String
Percent-decoding, with + read as a space. A malformed escape is kept as written.
(Route.decode("caf%C3%A9+au+lait"), Route.decode("100%zz"))
("café au lait", "100%zz")
Internal helpers
These are reachable — nib has no private functions — but they are the module's own plumbing, not an interface it promises to keep.
8 signature(s)
data Picked where Picked(Route.Rule, Map<String, String>); Nothing
func consider :: acc: Route.Picked, rt: Route.Rule, method: String, p: String -> Route.Picked
func match_parts :: ps: Vec<String>, xs: Vec<String>, i: Int, got: Map<String, String> -> Route.Match
func join_from :: xs: Vec<String>, i: Int -> String raises Err.IndexOutOfRange
func add_pair :: m: Map<String, String>, part: String -> Map<String, String>
func decode_from :: b: Bytes, i: Int, j: Int, n: Int -> String raises Err.IndexOutOfRange, Err.OutOfRange
func hex :: c: Int -> Int
func cut :: s: String, from: Int, to: Int -> String