将选项从 Plug.Router 转发到另一个 Plug.Router

Forward options from a Plug.Router to another Plug.Router

背景

我有一个 Plug.Router 应用程序可以接收一些选项。我需要通过 forward 将这些选项传递给其他插件,但我不知道该怎么做。

代码

这是主路由器。它接收请求并决定将它们转发到哪里。

defmodule MyApp.Web.Router do
  use Plug.Router

  plug(:match)
  plug(:dispatch)

  #Here I check that I get options! 
  def init(father_opts), do: IO.puts("#{__MODULE__} => #{inspect father_opts}")

  forward "/api/v1", to: MyApp.Web.Route.API.V1, init_opts: father_opts??
end

正如您可能猜到的那样,这是行不通的。我希望我的 forward 呼叫访问此路由器正在接收的 father_opts,但我无法访问它们。

起初我想到了以下代码片段:

def init(opts), do: opts

def call(conn, father_opts) do
  forward "/api/v1", to: MyApp.Web.Route.API.V1, init_opts: father_opts
end

但这不起作用,因为我无法将 forward 放入 call

那么如何使用 forward 实现我的 objective?

有一个选项添加了一个顶级插件,它将在 private 上存储父亲选项,您可以在子 call 上获取它。

类似于:

defmodule Example.Router do
  def init(opts), do: opts
  def call(conn, options) do
    Example.RouterMatch.call(Plug.Conn.put_private(conn, :father_options, options), Example.RouterMatch.init(options))
  end
end

defmodule Example.RouterMatch do
  use Plug.Router

  plug :match
  plug :dispatch

  forward "/check", to: Example.Route.Check
  forward "/dispatch", to: Example.Plug.Dispatch
end

然后您可以在 Example.Route.Check.call/2.

中的 conn 上获取选项