mirror of
https://github.com/c-cube/tiny_httpd.git
synced 2025-12-05 19:00:32 -05:00
feat headers: expose parsing helper
This commit is contained in:
parent
bde09435b4
commit
e1bfe70991
2 changed files with 23 additions and 10 deletions
|
|
@ -46,6 +46,21 @@ let for_all pred s =
|
|||
true
|
||||
with Exit -> false
|
||||
|
||||
let parse_line_ (line : string) : _ result =
|
||||
try
|
||||
let i =
|
||||
try String.index line ':'
|
||||
with Not_found -> failwith "invalid header, missing ':'"
|
||||
in
|
||||
let k = String.sub line 0 i in
|
||||
if not (for_all is_tchar k) then
|
||||
failwith (Printf.sprintf "Invalid header key: %S" k);
|
||||
let v =
|
||||
String.sub line (i + 1) (String.length line - i - 1) |> String.trim
|
||||
in
|
||||
Ok (k, v)
|
||||
with Failure msg -> Error msg
|
||||
|
||||
let parse_ ~(buf : Buf.t) (bs : IO.Input.t) : t =
|
||||
let rec loop acc =
|
||||
match IO.Input.read_line_using_opt ~buf bs with
|
||||
|
|
@ -56,16 +71,10 @@ let parse_ ~(buf : Buf.t) (bs : IO.Input.t) : t =
|
|||
bad_reqf 400 "bad header line, not ended in CRLF"
|
||||
| Some line ->
|
||||
let k, v =
|
||||
try
|
||||
let i = String.index line ':' in
|
||||
let k = String.sub line 0 i in
|
||||
if not (for_all is_tchar k) then
|
||||
invalid_arg (Printf.sprintf "Invalid header key: %S" k);
|
||||
let v =
|
||||
String.sub line (i + 1) (String.length line - i - 1) |> String.trim
|
||||
in
|
||||
k, v
|
||||
with _ -> bad_reqf 400 "invalid header line: %S" line
|
||||
match parse_line_ line with
|
||||
| Ok r -> r
|
||||
| Error msg ->
|
||||
bad_reqf 400 "invalid header line: %s\nline is: %S" msg line
|
||||
in
|
||||
loop ((String.lowercase_ascii k, v) :: acc)
|
||||
in
|
||||
|
|
|
|||
|
|
@ -33,3 +33,7 @@ val pp : Format.formatter -> t -> unit
|
|||
(** Pretty print the headers. *)
|
||||
|
||||
val parse_ : buf:Buf.t -> IO.Input.t -> t
|
||||
(**/*)
|
||||
|
||||
val parse_line_ : string -> (string * string, string) result
|
||||
(**/*)
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue