forked from ye-man/fnm
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathHttp.re
42 lines (35 loc) · 1017 Bytes
/
Http.re
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
open Lwt;
open Cohttp;
open Cohttp_lwt_unix;
type response = {
body: string,
status: int,
};
let body = response => response.body;
let status = response => response.status;
exception Not_found(response);
let throwOnKnownErrors =
fun
| {status: 404, _} as r => Lwt.fail(Not_found(r))
| r => Lwt.return(r);
let rec makeRequest = url =>
Uri.of_string(url)
|> Cohttp_lwt_unix.Client.get
>>= (
((resp, body)) => {
let status = resp |> Response.status;
let code_of_status = status |> Code.code_of_status;
let location = resp |> Response.headers |> Header.get_location;
switch (Code.is_redirection(code_of_status), location) {
| (true, Some(uri)) => makeRequest(Uri.to_string(uri))
| _ =>
let%lwt body = body |> Cohttp_lwt.Body.to_string;
throwOnKnownErrors({status: code_of_status, body});
};
}
);
let download = (url, ~into) => {
let%lwt _ =
makeRequest(url) >>= (({body, _}) => Fs.writeFile(into, body));
Lwt.return();
};