Is there a way to have a Phoenix Plug just for one route?

∥☆過路亽.° 提交于 2020-05-15 08:11:44

问题


In Phoenix I have my routes as follow :

  scope "/", ManaWeb do
    pipe_through [:browser, :auth]
    get "/register",  RegistrationController, :new
    post "/register", RegistrationController, :register
  end

However I would like to set a Plug for the last route (POST).

How would I go about that with current tools ?


回答1:


As it is stated in the documentation for Phoenix.Router.pipeline/2

Every time pipe_through/1 is called, the new pipelines are appended to the ones previously given.

That said, this would work:

scope "/", ManaWeb do
  pipe_through [:browser, :auth]
  get "/register",  RegistrationController, :new

  pipe_through :post_plug
  post "/register", RegistrationController, :register
end



回答2:


Another solution would be using the plug directly in the controller

defmodule ManaWeb.RegistrationController do
  # import the post_plug...
  plug :post_plug when action in [:register]

  def register(conn, params) do
    # ...
  end
end


来源:https://stackoverflow.com/questions/60996561/is-there-a-way-to-have-a-phoenix-plug-just-for-one-route

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!