File: client_lwt_timeout.ml

package info (click to toggle)
ocaml-cohttp 5.3.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,088 kB
  • sloc: ml: 7,793; javascript: 15; makefile: 12
file content (26 lines) | stat: -rw-r--r-- 793 bytes parent folder | download | duplicates (3)
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
open Lwt
open Cohttp
open Cohttp_lwt_unix

let compute ~time ~f =
  Lwt.pick
    [
      (f () >|= fun v -> `Done v); (Lwt_unix.sleep time >|= fun () -> `Timeout);
    ]

let body =
  let get () = Client.get (Uri.of_string "https://www.reddit.com/") in
  compute ~time:0.1 ~f:get >>= function
  | `Timeout -> Lwt.fail_with "Timeout expired"
  | `Done (resp, body) ->
      let code = resp |> Response.status |> Code.code_of_status in
      Printf.printf "Response code: %d\n" code;
      Printf.printf "Headers: %s\n"
        (resp |> Response.headers |> Header.to_string);
      body |> Cohttp_lwt.Body.to_string >|= fun body ->
      Printf.printf "Body of length: %d\n" (String.length body);
      body

let () =
  let body = Lwt_main.run body in
  print_endline ("Received body\n" ^ body)