1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
module Body = Cohttp.Body
module Transfer = Cohttp.Transfer
open Lwt
type t = [ Body.t | `Stream of (string Lwt_stream.t[@sexp.opaque]) ]
[@@deriving sexp]
let empty = (Body.empty :> t)
let create_stream fn arg =
let fin = ref false in
Lwt_stream.from (fun () ->
match !fin with
| true -> return_none
| false -> (
fn arg >>= function
| Transfer.Done -> return_none
| Final_chunk c ->
fin := true;
return (Some c)
| Chunk c -> return (Some c)))
let is_empty (body : t) =
match body with
| #Body.t as body -> return (Body.is_empty body)
| `Stream s ->
Lwt_stream.get_while (fun x -> x = "") s >>= fun _ ->
Lwt_stream.is_empty s
let to_string (body : t) =
match body with
| #Body.t as body -> return (Body.to_string body)
| `Stream s ->
let b = Buffer.create 1024 in
Lwt_stream.iter (Buffer.add_string b) s >>= fun () ->
return (Buffer.contents b)
let to_string_list (body : t) =
match body with
| #Body.t as body -> return (Body.to_string_list body)
| `Stream s -> Lwt_stream.to_list s
let of_string s = (Body.of_string s :> t)
let to_stream (body : t) =
match body with
| `Empty -> Lwt_stream.of_list []
| `Stream s -> s
| `String s -> Lwt_stream.of_list [ s ]
| `Strings sl -> Lwt_stream.of_list sl
let drain_body (body : t) =
match body with
| `Empty | `String _ | `Strings _ -> return_unit
| `Stream s -> Lwt_stream.junk_while (fun _ -> true) s
let of_string_list l = `Strings l
let of_stream s = `Stream s
let transfer_encoding = function
| #Body.t as t -> Body.transfer_encoding t
| `Stream _ -> Transfer.Chunked
let length (body : t) : (int64 * t) Lwt.t =
match body with
| #Body.t as body -> return (Body.length body, body)
| `Stream _ ->
to_string body >>= fun buf ->
let len = Int64.of_int (String.length buf) in
return (len, `String buf)
let write_body fn = function
| `Empty -> return_unit
| `Stream st -> Lwt_stream.iter_s fn st
| `String s -> fn s
| `Strings sl -> Lwt_list.iter_s fn sl
let map f t =
match t with
| #Body.t as t -> (Body.map f t :> t)
| `Stream s -> `Stream (Lwt_stream.map f s)
let to_form (body : t) = to_string body >|= Uri.query_of_encoded
let of_form ?scheme f = Uri.encoded_of_query ?scheme f |> of_string