编译 en Elixir 程序时执行的函数

Function executed while compiling en Elixir program

我有这种奇怪的行为,让我抓狂! 我有以下插件,它检查 API 客户端是否实际在 x-api-key header 中提供了正确的 API 密钥:

defmodule APIServer.APIKeyAuthPlug do

  # import Plug.Conn
  require Logger
  alias APIServer.Util

  def init(opts) do
    {:ok, options} = opts[:auth]
    apikey = options[:apikey]
    Logger.debug("API key is #{inspect(apikey)}")
    apikey
  end
  
  def call(conn, key) do
    conn_key = Plug.Conn.get_req_header(conn, "x-api-key") |> hd
    Logger.debug("Registered key #{inspect(key)}")
    # rest of the call function
  end
end

插件插入路由器中的插件链:

  plug Plug.Logger, log: :info
  plug APIKeyAuthPlug,
    auth: Application.fetch_env(:probe_server,  APIServer.APIKeyAuthPlug)
  plug(:match)
  plug(:dispatch)

并且正确的密钥本身被定义为 en 环境变量并在 config.exs:

中读取
config :api_server,  APIServer.APIKeyAuthPlug,
  apikey: System.get_env("API_SERVER_APIKEY") || "XYZ"

现在,当我编译该代码时,init 函数(且仅该函数)中的行 Logger.debug("API key is #{inspect(apikey)}") 得到实际执行:

maurycy@kali> mix compile
Compiling 2 files (.ex)

16:17:59.774 [debug] API key is "XYZ"

有什么想法吗?

Plug.Builder.plug/2 (plug APIKeyAuthPlug, ...) in the router results in the call to init/1 during compilation time unless mode is explicitly set to :runtime instead of default :compile https://github.com/elixir-plug/plug/blob/v1.11.1/lib/plug/builder.ex#L275

的调用

设置 init_mode: :runtime 将解决问题。