Hcs.Router
hcs · API reference
Path router with method matching, parameters, wildcards, route scopes, and per-route plug pipelines.
Use Router.empty plus Router.add_route for mutable construction, or Router.Route.* with Router.compile for declarative route lists. Route handlers receive path parameters plus the original Server.request.
HTTP route matching.
The router maps method/path pairs to handlers and path parameters. Paths may include named parameters such as "/users/:id" and a trailing wildcard "/assets/*".
Example:
let router = Hcs.Router.empty () in
Hcs.Router.add_route router ~method_:(Some `GET) ~path:"/users/:id"
~plugs:Hcs.Pipeline.empty ~handler:(fun params req ->
match Hcs.Router.param "id" params with
| Some id -> Hcs.Response.text id
| None -> Hcs.Response.bad_request ())type segment =
| Literal of string
| Param of string
| Wildcard (* Parsed route path segment. *)type params = (string * string) listCaptured path parameters.
type 'a handler_entry = {
handler : 'a;
plugs : Pipeline.t;
}Handler plus route-specific plugs.
type 'a trie_node = {
mutable handlers : (Method.t option * 'a handler_entry) list;
literal_children : (string, 'a trie_node) Hashtbl.t;
mutable param_child : (string * 'a trie_node) option;
mutable wildcard_child : 'a trie_node option;
}Router trie node. Exposed for existing callers; prefer router operations.
type 'a t = {
root : 'a trie_node;
}Mutable router.
type 'a match_result = {
handler : 'a;
params : params;
plugs : Pipeline.t;
}Result of a successful lookup.
val empty : unit -> 'a tCreate an empty router.
val parse_path : string -> segment listParse a route pattern into segments.
val add_route :
'a t ->
method_:Method.t option ->
path:string ->
handler:'a ->
plugs:Pipeline.t ->
unitAdd a route. method_=None matches any method.
val lookup : 'a t -> method_:Method.t -> path:string -> 'a match_result optionFind a route for an incoming method/path.
module Route : sig ... endval normalize_path : string -> stringval join_paths : string -> string -> stringPath helpers used by scopes.
val scope : ?through:Pipeline.t -> string -> 'a Route.t list -> 'a Route.t listPrefix routes and compose a shared pipeline into each route.
val compile : 'a Route.t list -> 'a tCompile declarative routes into a mutable router.
val compile_scopes : 'a Route.t list list -> 'a tCompile multiple scoped route lists.
val param : string -> params -> string optionval param_or : string -> default:string -> params -> stringval param_int : string -> params -> int optionval param_int_or : string -> default:int -> params -> intCaptured path parameter helpers.