gpt4 book ai didi

elixir - 在 Plug.Router 中 init 函数的意义是什么?

转载 作者:行者123 更新时间:2023-12-01 23:54:38 27 4
gpt4 key购买 nike

尝试了解 Plug,特别是 Plug.Router。来自文档(http://hexdocs.pm/plug/Plug.Router.html)。根据规范,插件有一个 init 函数,该函数在初始化时调用以传递选项,但这些选项似乎在定义的路由中不可用。

没有可用选项的原因是什么?是否有一种模式可以实现这一点?

最佳答案

这里摘录自《Programming Phoenix》一书:

“有时,您可能需要 Phoenix 做一些繁重的工作来转换选项。这是 init 函数的工作。init 在编译时发生。Plug 将使用 init 的结果作为第二个call 的参数。因为 init 通常在编译时调用,所以它是验证选项和准备一些工作的完美场所。这样,call 可以尽可能快。由于 call 是主力,我们希望它做尽可能少的工作。”

例如 - 在 paths.ex 文件中使用插件

  pipeline :api do
plug :accepts, ["json"]
plug Example.Authenticated, repo: Example.Repo
end

repo:Example.Repo 是传递给Example.Repo 内的init 函数的选项

defmodule Example.Authenticated do
import Plug.Conn

def init(opts) do
Keyword.fetch!(opts, :repo)
end

def call(conn, repo) do
...
end

end

我假设在 Plug.Router 的情况下 - 在编译时修改可能是 - 加载构建/修改路由的模块 - 可能来自外部源?取决于您想要实现的目标。

关于elixir - 在 Plug.Router 中 init 函数的意义是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35053332/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com