forked from wojtekmach/mix_install_examples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathc_libcurl.exs
60 lines (45 loc) · 1.08 KB
/
c_libcurl.exs
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
Mix.install([
{:c, github: "wojtekmach/c"}
])
defmodule Curl.MixProject do
use Mix.Project
def project do
[
app: :curl,
version: "1.0.0"
]
end
end
defmodule Main do
def main do
Curl.test()
end
end
defmodule Curl do
use C, compile: "-lcurl"
# Based on https://curl.se/libcurl/c/simple.html
defc(:test, 0, ~S"""
#include <curl/curl.h>
static ERL_NIF_TERM test(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
{
CURL *curl;
CURLcode res;
curl = curl_easy_init();
if (!curl) {
enif_raise_exception(env, enif_make_string(env, "could not init curl", ERL_NIF_LATIN1));
return -1;
}
curl_easy_setopt(curl, CURLOPT_URL, "https://httpbin.org/json");
/* Perform the request, res will get the return code */
res = curl_easy_perform(curl);
/* Check for errors */
if (res != CURLE_OK) {
fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
}
/* always cleanup */
curl_easy_cleanup(curl);
return enif_make_atom(env, "ok");
}
""")
end
Main.main()