diff --git a/.gitignore b/.gitignore index 2272a4c..dd1447f 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ checksum-Elixir.RustlerPrecompilationExample.Native.exs +_build diff --git a/c_libcurl.exs b/c_libcurl.exs new file mode 100644 index 0000000..fb89eb6 --- /dev/null +++ b/c_libcurl.exs @@ -0,0 +1,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 + + 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()