Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
# in your app supervisor
:phx_dyn_dispatch = :ets.new(:phx_dyn_dispatch, [:named_table, :bag, :public])
defmodule DynamicDispatch do
def register(group, plug, opts) do
true = :ets.insert(:phx_dyn_dispatch, {group, plug, opts})
end
def unregister(group, plug) do
true = :ets.match_delete(:phx_dyn_dispatch, {group, plug, :_})
end
def init(opts), do: opts
def call(conn, group: group) do
Enum.reduce_while(:ets.lookup(:phx_dyn_dispatch, group), conn, fn
{_, _plug, _opts}, %Plug.Conn{halted: true} = acc -> {:halt, acc}
{_, plug, opts}, %Plug.Conn{} = acc -> {:cont, plug.call(acc, opts)}
end)
end
end
# in your existing router
forward "/", DynamicDispatch, []
# register your router/plug at any time
DynamicDispatch.register(:app, MyOtherRouter, [])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment