feat route: add to_url, to produce a URL path from a route

provide arguments and get the corresponding path, which makes
it easy to build a full URL if needed.
This commit is contained in:
Simon Cruanes 2025-06-06 22:25:01 -04:00
parent 023805232f
commit 03c3e09f12
No known key found for this signature in database
GPG key ID: EBFFF6F283F3A2B4
2 changed files with 21 additions and 0 deletions

View file

@ -91,3 +91,22 @@ module Private_ = struct
end
let pp out x = Format.pp_print_string out (to_string x)
let rec to_url_rec : type b. Buffer.t -> (b, string) t -> b =
fun buf route ->
match route with
| Fire -> Buffer.contents buf
| Rest {url_encoded=_} ->
(fun str -> Buffer.add_string buf str; Buffer.contents buf)
| Compose (comp, rest) ->
(match comp with
| Exact s -> Buffer.add_string buf s; Buffer.add_char buf '/'; to_url_rec buf rest
| Int -> (fun i -> Printf.bprintf buf "%d/" i; to_url_rec buf rest)
| String ->
(fun s -> Printf.bprintf buf "%s/" s; to_url_rec buf rest)
| String_urlencoded ->
(fun s -> Printf.bprintf buf "%s/" (Util.percent_encode s); to_url_rec buf rest))
let to_url (h: ('a, string) t) : 'a =
let buf = Buffer.create 16 in
to_url_rec buf h

View file

@ -53,6 +53,8 @@ val to_string : _ t -> string
(** Print the route.
@since 0.7 *)
val to_url : ('a, string) t -> 'a
module Private_ : sig
val eval : string list -> ('a, 'b) t -> 'a -> 'b option
end