Skip to content

Commit 03c3e09

Browse files
committed
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.
1 parent 0238052 commit 03c3e09

File tree

2 files changed

+21
-0
lines changed

2 files changed

+21
-0
lines changed

src/core/route.ml

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,3 +91,22 @@ module Private_ = struct
9191
end
9292

9393
let pp out x = Format.pp_print_string out (to_string x)
94+
95+
let rec to_url_rec : type b. Buffer.t -> (b, string) t -> b =
96+
fun buf route ->
97+
match route with
98+
| Fire -> Buffer.contents buf
99+
| Rest {url_encoded=_} ->
100+
(fun str -> Buffer.add_string buf str; Buffer.contents buf)
101+
| Compose (comp, rest) ->
102+
(match comp with
103+
| Exact s -> Buffer.add_string buf s; Buffer.add_char buf '/'; to_url_rec buf rest
104+
| Int -> (fun i -> Printf.bprintf buf "%d/" i; to_url_rec buf rest)
105+
| String ->
106+
(fun s -> Printf.bprintf buf "%s/" s; to_url_rec buf rest)
107+
| String_urlencoded ->
108+
(fun s -> Printf.bprintf buf "%s/" (Util.percent_encode s); to_url_rec buf rest))
109+
110+
let to_url (h: ('a, string) t) : 'a =
111+
let buf = Buffer.create 16 in
112+
to_url_rec buf h

src/core/route.mli

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,8 @@ val to_string : _ t -> string
5353
(** Print the route.
5454
@since 0.7 *)
5555

56+
val to_url : ('a, string) t -> 'a
57+
5658
module Private_ : sig
5759
val eval : string list -> ('a, 'b) t -> 'a -> 'b option
5860
end

0 commit comments

Comments
 (0)