Proposal to add generic/matched route to Plug.Conn

Say we have the following router definition

get "/user/:id", UserController, :show

and we have the api request /user/some-id. We can get already the current path from the Plug connection but we cannot get the matched routed from my knowledge.

Getting the matched routed would be nice so that if we persist all requests for analytical purpose we could also save the matched route with the actual route, something like:

route | matched_route | duration_ms | created_at | status | method

That would allow for some nice analytics.

If that is already possible, I would appreciate if someone can point me in that correct direction otherwise I would happily take a look at implementing it.

You can fetch most if not all of those data. First of all Phoenix somehow needs to know what should be applied and there is no magic here. Simply Phoenix stores those data somewhere. Where exactly … it’s private - I mean the field in Plug.Conn struct. :wink:

Following naming private you should not access those data unless some public function do that for you as there is no guarantee that the structure of private data would be kept in next releases.

I would recommend to check the documentation, just for example we have: Phoenix.Controller.action_name/1. If you take a look at source code it fetches a value of phoenix_action from private data:

In same module there are functions to fetch Controller, Endpoint and Router modules.

The Router also allows you to fetch routing information using Phoenix.Router.routes/1

Take a deep look at Phoenix documentation and find things you think would be useful for your use case.

I see, Phoenix.Router.route_info(conn.private[:phoenix_router], conn.method, conn.request_path, "") should do the trick, thanks.

1 Like

Instead of doing the lookup twice you could also use Plug.Conn.register_before_send and pull out the information you need from the conn, which should then be available.

2 Likes