使用HTTPoison初始化模块属性

lap*_*ira 2 elixir httpoison

我正在尝试像这样初始化模块属性

  response = HTTPoison.get! url
  {:ok, response} = Poison.decode(response.body)
  @attr response
Run Code Online (Sandbox Code Playgroud)

我以前用一个文件来做,就像这样:

  @external_resource file = Path.join([__DIR__, "file.txt"])
  Module.register_attribute __MODULE__, :attr, accumulate: true

  for line <- File.stream!(file, [], :line) do
    @attr line
    ...
Run Code Online (Sandbox Code Playgroud)

使用HTTPoison并获取API的响应是否一样?我收到此错误:

== Compilation error in file lib/module.ex ==
** (ArgumentError) argument error
    (stdlib) :ets.lookup_element(:hackney_config, :mod_metrics, 2)
    /project/deps/hackney/src/hackney_metrics.erl:27: :hackney_metrics.get_engine/0
    /project/deps/hackney/src/hackney_connect.erl:69: :hackney_connect.create_connection/5
    /project/deps/hackney/src/hackney_connect.erl:37: :hackney_connect.connect/5
    /project/deps/hackney/src/hackney.erl:316: :hackney.request/5
    lib/httpoison/base.ex:630: HTTPoison.Base.request/9
    lib/httpoison.ex:66: HTTPoison.request!/5
    lib/module.ex:4: (module)
Run Code Online (Sandbox Code Playgroud)

Dog*_*ert 5

依赖应用程序不会在编译时自动启动。您需要先明确地开始HTTPoison使用它:

HTTPoison.start()
response = HTTPoison.get! url
{:ok, response} = Poison.decode(response.body)
@attr response
Run Code Online (Sandbox Code Playgroud)