mirror of
https://github.com/c-cube/tiny_httpd.git
synced 2025-12-06 11:15:35 -05:00
feat: add Tiny_httpd_util.parse_query for query decoding
This commit is contained in:
parent
9eae697ded
commit
b0dbc1c057
2 changed files with 34 additions and 0 deletions
|
|
@ -35,3 +35,31 @@ let percent_decode (s:string) : _ option =
|
|||
Some (Buffer.contents buf)
|
||||
with Exit -> None
|
||||
|
||||
|
||||
let parse_query s : (_ list, _) result=
|
||||
let pairs = ref [] in
|
||||
let is_sep_ = function '&' | ';' -> true | _ -> false in
|
||||
try
|
||||
let i = ref 0 in
|
||||
let j = ref 0 in
|
||||
let parse_pair () =
|
||||
let eq = String.index_from s !i '=' in
|
||||
let k = String.sub s !i (eq- !i) in
|
||||
let v = String.sub s (eq+1) (!j-eq-1) in
|
||||
pairs := (k,v) :: !pairs;
|
||||
in
|
||||
while !i < String.length s do
|
||||
while !j < String.length s && not (is_sep_ (String.get s !j)) do incr j done;
|
||||
if !j < String.length s then (
|
||||
assert (is_sep_ (String.get s !j));
|
||||
parse_pair();
|
||||
i := !j+1;
|
||||
j := !i;
|
||||
) else (
|
||||
parse_pair();
|
||||
i := String.length s; (* done *)
|
||||
)
|
||||
done;
|
||||
Ok !pairs
|
||||
with e -> Error e
|
||||
|
||||
|
|
|
|||
|
|
@ -12,3 +12,9 @@ val percent_encode : ?skip:(char -> bool) -> string -> string
|
|||
val percent_decode : string -> string option
|
||||
(** Inverse operation of {!percent_encode}.
|
||||
Can fail since some strings are not valid percent encodings. *)
|
||||
|
||||
val parse_query : string -> ((string*string) list, exn) result
|
||||
(** Parse a query as a list of ['&'] or [';'] separated [key=value] pairs.
|
||||
The order might not be preserved.
|
||||
@since 0.3
|
||||
*)
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue