Mojolicious路由(十五)
一、重新安排routes
从应用启动到第一个请求到达,所有的路由仍然可以通过Mojolicious:: routes::Route中的”add_child”和Mojolicious:: routes::Route中的”remove”方法移动甚至删除。
# GET /example/show -> {controller => 'example', action => 'show'}
my $show = $r->get('/show')->to('example#show');
$r->any('/example')->add_child($show);
# Nothing
$r->get('/secrets/show')->to('secrets#show')->name('show_secrets');
$r->find('show_secrets')->remove;
这对于重新安排插件创建的路由是非常有用的,我们可以使用Mojolicious:: routes::Route中的“find”来根据名称查找路由。
# GET /example/test -> {controller => 'example', action => 'test'}
$r->get('/something/else')->to('something#else')->name('test');
my $test = $r->find('test');
$test->pattern->parse('/example/test');
$test->pattern->defaults({controller => 'example', action => 'test'});
即使是路由模式和目的地也可以通过Mojolicious::Routes::模式中的”parse”和Mojolicious::Routes::模式中的”defaults”来更改。
二、添加条件
我们也可以用Mojolicious::Routes中的add_condition方法来添加自己的条件。所有的条件基本上都是路由器插件,每次有新的请求到达时都会运行,并且需要返回一个真值来匹配路由。
# A condition that randomly allows a route to match
$r->add_condition(random => sub ($route, $c, $captures, $num) {
# Loser
return undef if int rand $num;
# Winner
return 1;
});
# /maybe (25% chance)
$r->get('/maybe')->requires(random => 4)->to('foo#bar');
使用任何我们需要的请求信息。
# A condition to check query parameters (useful for mock web services)
$r->add_condition(query => sub ($route, $c, $captures, $hash) {
for my $key (keys %$hash) {
my $param = $c->req->url->query->param($key);
return undef unless defined $param && $param eq $hash->{$key};
}
return 1;
});
# /hello?to=world&test=1
$r->get('/hello')->requires(query => {test => 1, to => 'world'})->to('foo#bar');