繁体   English   中英

使用Plug.Router语法在init上传递的Plug,use选项

[英]Plug, use option passed at init with Plug.Router syntax

我正在使用Plug,我想了解。

我的代码看起来像:

defmodule Numerino.Plug do
  use Plug.Router
  use Plug.Debugger

  plug :put_resp_content_type, "application/json"
  plug :match
  plug :dispatch

  def init options do
    IO.inspect options
    options
  end

  get "/" do
    conn
    |> IO.inspect
    |> send_resp(201, "world")
  end

  match _ do
    send_resp(conn, 404, "Not found.")
  end

end

在get中我需要使用作为参数传递的option

如何访问保持相同Plug.Router语法的选项?

你没有说明你为什么要这样做,所以我只能给出一个通用的答案。 如果您有特定用例,那么可能有更好的解决方案。


您可以通过向路由器添加一个附加插件来实现此目的,该插件将选项存储在conn的私有存储中:

plug :opts_to_private

defp opts_to_private(conn, opts) do
  put_private(conn, :my_app_opts, opts)
end

然后可以使用conn.private.my_app_opts在您的路径中访问conn.private.my_app_opts

get "/" do
  conn.private.my_app_opts
  |> IO.inspect

  conn
  |> send_resp(201, "world")
end

dispatch函数是defoverridable / 1所以你也可以通过覆盖函数来做同样的事情:

defp dispatch(conn, opts) do
  conn = put_private(conn, :my_app_opts, opts)
  super(conn, opts)
end

但是我发现定义了一个新函数,例如opts_to_private cleaner。

您只需覆盖呼叫回调:

  def call(conn, opts) do
    put_private(conn, :opts, opts)
    |> super(opts)
  end

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM