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) list

Captured 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 t

Create an empty router.

val parse_path : string -> segment list

Parse a route pattern into segments.

val add_route : 
  'a t ->
  method_:Method.t option ->
  path:string ->
  handler:'a ->
  plugs:Pipeline.t ->
  unit

Add a route. method_=None matches any method.

val lookup : 'a t -> method_:Method.t -> path:string -> 'a match_result option

Find a route for an incoming method/path.

module Route : sig ... end
val normalize_path : string -> string
val join_paths : string -> string -> string

Path helpers used by scopes.

val scope : ?through:Pipeline.t -> string -> 'a Route.t list -> 'a Route.t list

Prefix routes and compose a shared pipeline into each route.

val compile : 'a Route.t list -> 'a t

Compile declarative routes into a mutable router.

val compile_scopes : 'a Route.t list list -> 'a t

Compile multiple scoped route lists.

val param : string -> params -> string option
val param_or : string -> default:string -> params -> string
val param_int : string -> params -> int option
val param_int_or : string -> default:int -> params -> int

Captured path parameter helpers.