Plug, use option passed to init with Plug.Router syntax

I am using Plug and I would like to understand.

My code looks like this:

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

Inside get, I will need to use the argument optionpassed as the argument.

How do I access parameters that support the same Plug.Router syntax?

+4
source share
1 answer

You did not indicate why you want to do this, so I can give a general answer. If you have a specific use case, then there may be a better solution.


You can do this by adding an additional plug to the router, which stores options in the conn private storage:

plug :opts_to_private

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

This will then be available on your routes with conn.private.my_app_opts:

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

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

defoverridable/1, , :

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

, opts_to_private cleaner.

+3

Source: https://habr.com/ru/post/1611265/


All Articles