How to add a plugin to Elixir / Phoenix in front of the router?

Is there a way to insert a plug to start before the router selects the controller / action? I have an application that will be redirected to the root path for certain subdomains, regardless of the current path in these domains. So:

sub.myapp.com/foo/bar should redirect to sub.myapp.com/

But by default, the router says that there is no /foo/bar path, and it stops my traffic jams, that is, it never hits my redirect.

Is there a way to insert my plug in front of the router by selecting an action / controller?

(Note: I'm sure I can handle this case with the catch route for everyone , but I'm just wondering if there is a better way.)

+7
elixir phoenix-framework
source share
1 answer

Your router is explicitly called in lib/my_app/endpoint.ex . Prior to this, you can add any plugins to this file.

You can write a plug-in that handles redirects and stops the connection before the router is called.

 defmodule HelloPhoenix.Endpoint do use Phoenix.Endpoint, otp_app: :hello_phoenix plug Plug.RequestId plug Plug.Logger ... plug CustomRedirectPlug # Add your plug here plug HelloPhoenix.Router end 
+9
source share

All Articles