3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

mix_install_examplesからc_libcurl.exs の紹介です(Elixir)

Posted at

ちぎりきなかたみに袖をしぼりつつ末の松山波越さじとは

Advent Calendar 2022 93日目1の記事です。
I'm looking forward to 12/25,2022 :santa::santa_tone1::santa_tone2::santa_tone3::santa_tone4::santa_tone5:
私のAdvent Calendar 2022 一覧


はじめに

Elixirを楽しんでいますか:bangbang::bangbang::bangbang:

Mix.install/2のサンプル集であるmix_install_examplesからwojtekmach/cを紹介します。

What's Mix.install/2 ?

Mix.install/2は、Elixir 1.12から追加されました。
Elixirでライブラリ(Hex)を追加するのは、1.11まではmix newでプロジェクトを作らないといけないなど、ひと手間必要でした。
Mix.install/2を使うことで、ちょっとした1ファイルで収まるようなスクリプトを書く際に.exsのみで完結できるようになりました。

具体例

具体例です。
私がよく使ういつものサンプルです。

Qiita APIを使わせていただいて、Elixirタグがついた最新の記事を20件取得しています

Mix.install [:req]

"https://qiita.com/api/v2/items?query=tag:Elixir"
|> URI.encode()
|> Req.get!(finch_options: [pool_timeout: 50000, receive_timeout: 50000])
|> Map.get(:body)
|> Enum.map(& Map.take(&1, ["title", "url"]))

Qiitaさん、いつもありがとうございます!!!


c_libcurl.exs

おもしろそうなサンプルってことで、今日はwojtekmach/cを楽しんでみます。

What's wojtekmach/c ?

Easily use C code in your Elixir projects.

には登録されていないようです。

Run

それでは、c_libcurl.exsを動かしてみます。

以下、そのまま掲載します。

c_libcurl.exs
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()

defcの第2引数に文字列でCのコードを埋め込んでいるところが特徴です。

実行

git clone https://github.com/wojtekmach/mix_install_examples.git
cd mix_install_examples
elixir c_libcurl.exs

結果

JSONが表示されました。
C言語のcurl_easy_performの実行のところで表示されていました。
前後にprintf("a")を入れて確かめました。

{
  "slideshow": {
    "author": "Yours Truly", 
    "date": "date of publication", 
    "slides": [
      {
        "title": "Wake up to WonderWidgets!", 
        "type": "all"
      }, 
      {
        "items": [
          "Why <em>WonderWidgets</em> are great", 
          "Who <em>buys</em> WonderWidgets"
        ], 
        "title": "Overview", 
        "type": "all"
      }
    ], 
    "title": "Sample Slide Show"
  }
}

https://httpbin.org/json
にブラウザでアクセスするなり、それこそcurl https://httpbin.org/jsonしたときに得られる結果と同じものが表示されました。

もしかしたら環境によってはCのコンパイラやcurl/curl.hを見れるようにするためにsomethingのインストールが必要になるかもしれません。
私はmacOSを使っていまして、Command line tools for Xcodeをインストールしています。
このへんで事足りたのだとおもいます。


Wrapping up :lgtm::lgtm::lgtm::lgtm::lgtm:

Enjoy Elixir:bangbang::bangbang::bangbang:
$\huge{Enjoy\ Elixir🚀}$

今回は、mix_install_examplesの中から、c_libcurl.exsをご紹介をしました。

今後も他のサンプルをご紹介していきます。
また、シンプルでいい例をおもいついたら、プルリクを送ってみるのはいいかもしれません。
私は、おもいついた場合には、プルリクを送ってみる気でいます :rocket::rocket::rocket:

以上です。


I organize autoracex.
And I take part in NervesJP, fukuoka.ex, EDI, tokyo.ex, Pelemay.
I hope someday you'll join us.

We Are The Alchemists, my friends!

  1. @kaizen_nagoya さんの「「@e99h2121 アドベントカレンダーではありますまいか Advent Calendar 2020」の改訂版ではありますまいか Advent Calendar 2022 1日目 Most Breakthrough Generator」から着想を得て、模倣いたしました。

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?