背景
我有一个接收一些选项的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实现我的目标呢?
发布于 2018-11-21 15:30:31
有一个选项添加了一个顶级插件,它将在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上的选项。
https://stackoverflow.com/questions/53414813
复制相似问题