1 (** curl lwt example *)
8 let printfn fmt
= ksprintf print_endline fmt
10 let curl_setup_simple h
=
12 set_useragent h
"Curl_lwt";
14 set_connecttimeout h
5;
16 set_followlocation h
false;
18 set_ipresolve h IPRESOLVE_V4
;
19 set_encoding h CURL_ENCODING_ANY
21 let curl_setup_tcp h
=
23 set_tcpkeepalive h
true;
29 let url = get_effectiveurl h
in
30 printfn "%3d %.2f %5.0fB URL: %s (%s)%s"
34 (if get_httpcode h
/ 100 = 3 then sprintf
"%s -> %s" url (get_redirecturl h
) else url)
36 (match code
with CURLE_OK
-> "" | _
-> sprintf
" %s (%d)" (strerror code
) (errno code
))
39 let b = Buffer.create
16 in
40 Curl.set_writefunction h
(fun s
-> Buffer.add_string
b s
; String.length s
);
41 Curl.set_prereqfunction h
(fun conn_primary_ip conn_local_ip conn_primary_port conn_local_port
->
42 printfn "Making request %s:%d -> %s:%d"
43 conn_local_ip conn_local_port conn_primary_ip conn_primary_port
;
45 Lwt.bind
(Curl_lwt.perform h
) (fun code
-> Lwt.return
(code
, Buffer.contents
b))
48 let h = Curl.init
() in
52 begin try%lwt
(* e.g. Canceled *)
53 let%lwt
(code
,_body
) = download h in
56 (* do something with body *)
58 printfn "EXN %s URL: %s" (Printexc.to_string exn
) url;
60 end[%lwt
.finally
Curl.cleanup
h; Lwt.return
()]
64 "http://www.forth.org.ru";
65 "http://caml.inria.fr";
66 "https://www.rust-lang.org";
68 "http://elm-lang.org";
69 "http://www.red-lang.org";
73 let%lwt
() = Lwt_unix.sleep
0.5 in
74 let%lwt
() = Lwt.choose tasks
in
75 print_endline
"Cancel remaining transfers";
79 printfn "Launch %d transfers" (List.length
urls);
80 let tasks = List.map
get urls in
81 Lwt_main.run
@@ Lwt.pick
[