How to find route name for given path in Mojolicious?

564 views Asked by At

When I parse html response body I want to find route names for all links found in the body. I use next code snippet:

    my $url =  Mojo::URL->new( $got );
    my $method =  uc( $url->query->clone->param( '_method' ) || 'GET' );
    my $c =  $t->app->build_controller;
    my $m =  Mojolicious::Routes::Match->new( root => $t->app->routes );

    $m->find( $c => { method => $method,  path => $url->path } );

Then $m->endpoint->name gives me the name of route.

But is there more simple way to find route name by given path?

I am looking for something like: $app->routes->find( '/api/v/users/146/link/7QRgs' ) which should return user_hash_check because I have next route:

$guest->get( '/users/:id/link/:hash', 'user_hash_check' )->to( 'user#hash_check' );
1

There are 1 answers

0
Eugen Konkov On

I have found only one place where we can find route by path. That is Mojolicious::Routes::Match and there is no other way to do this

The one ugly thing here to my mind is requirement to supply Mojolicious::Controller object. But controller is only required to make decision: dispatch or not dispatch Because it has extra info to make this decision: this is data to check conditions

The problem as I think is because of here are mixed two things:

  1. Request
  2. Path

And find should just return all routes matched against given arguments: path and method. Like selectors does The array result maybe cached (now routes with conditions are not cached)

Then dispatcher should check conditions against each route, not matcher. Here each condition may be called in context of right controller and not default one. And this will fix this issue. The routes have in most cases their own controller class have not?

Until this behavior will be fixed the example in the question is the best way to find routes