Hcs.Route

hcs · API reference

Typed, bidirectional routes: build a path once from combinators and use it both to register a handler (which receives typed captures) and to build URLs with Route.link. Compile-time-verified paths that compile down to Router.

Typed, bidirectional routes — compile-time-verified paths.

A route is built once from combinators and used both to register a handler (which receives the typed captures) and to build URLs with link. Because both directions come from the same value, a path cannot drift from its route, and a wrong capture type or arity is a compile error. Routes compile down to the string router, so Router.scope/Router.compile_scopes and pipelines are unchanged.

let ticket =
  Route.(s "tickets" / int) (* /tickets/:int *)
    (* register: the handler gets the typed capture *)
    Route.get ticket
    (fun id req -> show id req)
    (* build a URL, type-checked, from the same value *)
    Route.link ticket 42 (* "/tickets/42" *)
type ('f, 'r) t

A path whose captures are consumed by a function 'f producing 'r.

val s : string -> ('a, 'a) t

A literal segment, e.g. s "tickets". Captures nothing.

val int : (int -> 'a, 'a) t

Capture one path segment as an int.

val str : (string -> 'a, 'a) t

Capture one path segment as a string.

val (/) : ('a, 'b) t -> ('b, 'c) t -> ('a, 'c) t

Compose two paths left to right: s "tickets" / int / s "status" / str.

Build a URL from a route and its captures: link ticket 42 is "/tickets/42". The arity and types of the captures are checked by the compiler.

val pattern : ('f, 'r) t -> string

The underlying router pattern (captures shown as :p0, :p1, …). Mostly useful for debugging and tests.

type handler = Router.params -> Server.request -> Response.t
type route = handler Router.Route.t
val get : ('f, Server.request -> Response.t) t -> 'f -> route
val post : ('f, Server.request -> Response.t) t -> 'f -> route
val put : ('f, Server.request -> Response.t) t -> 'f -> route
val delete : ('f, Server.request -> Response.t) t -> 'f -> route
val patch : ('f, Server.request -> Response.t) t -> 'f -> route
val head : ('f, Server.request -> Response.t) t -> 'f -> route
val options : ('f, Server.request -> Response.t) t -> 'f -> route

Register a handler for a route. The handler is curried over the route's captures and then the request, e.g. a route with one int capture takes int -> Server.request -> Response.t. A capture that fails to parse (a non-integer in an int slot) yields a 404.