"Dynamic" routes in Mokholichesky

I would like to implement something like “dynamic” routes in my Mojolicious application. I have some predefined "static" routes and a DB table with URL aliases: '/ alias' → '/ URL'. Now I define the routes on the fly, and it looks like this:

before_dispatch => sub { my ($self, $controller) = @_; my $path = $controller->tx->req->url->path->to_string; if ( my $alias = $controller->app->model->alias->find({ alias => $path }) ) { my $match = Mojolicious::Routes::Match->new( get => $alias->{uri} ); my $routes = $controller->app->routes; $match->match( $routes ); $routes->route( $path )->to( $match->captures ); } 

But is there a better way?

+6
source share
1 answer

You add routes at runtime, which seems like a good approach (although you should probably check if a route exists before redefining it). You could also do this as catchall with a wildcard, then pass the request a bit later.

http://mojolicio.us/perldoc/Mojolicious/Guides/Routing#Wildcard_Placeholders

 $r->get('/(*everything)' )->to('mycontroller#aliases'); 
+4
source

Source: https://habr.com/ru/post/887368/


All Articles