Plug call function opts

Hi all

What are the values of opts parameter from plug:

  import Plug.Conn

  def init(opts), do: opts

  def call(conn, _opts) do

    conn
    |> put_resp_content_type("application/json")

  end

Thanks

2 Likes

Whatever is returned from init is passed in as the second parameter to call. init is run at compile time so that is where you’d put any heavy work to be done so that call isn’t slowed down at run time.

The opts param passed into init comes from whatever values you give the plug in your code. For example, plug MyApp.Plug, repo: MyApp.Repo would cause init to be run with [repo: MyApp.Repo] as the opts param. I could then use my passed in repo to get data ready for when the plug is actually invoked or I could just pass the repo as the second param to call if that’s all I needed.

3 Likes