Mojolicious路由(三)

一、通配符占位符

通配符占位符就像上面的两种类型的占位符,但是使用星号前缀并匹配所有内容,包括/和.,类似于正则表达式(.+)。

/hello              -> /*name/hello -> undef
/sebastian/23/hello -> /*name/hello -> {name => 'sebastian/23'}
/sebastian.23/hello -> /*name/hello -> {name => 'sebastian.23'}
/sebastian/hello    -> /*name/hello -> {name => 'sebastian'}
/sebastian23/hello  -> /*name/hello -> {name => 'sebastian23'}
/sebastian 23/hello -> /*name/hello -> {name => 'sebastian 23'}

它们对于手动匹配整个文件路径很有用。

/music/rock/song.mp3 -> /music/*filepath -> {filepath => 'rock/song.mp3'}

二、最小路由

Mojolicious中的“routes”属性包含一个可以用来生成路由结构的路由器。

# Application
package MyApp;
use Mojo::Base 'Mojolicious', -signatures;

sub startup ($self) {
  # Router
  my $r = $self->routes;

  # Route
  $r->get('/welcome')->to(controller => 'foo', action => 'welcome');
}

1;

上面的最小路由将加载并实例化MyApp::Controller::Foo类,并调用它的welcome方法。路由通常在application类的startup方法中配置,但是可以从任何地方访问路由器(甚至在运行时)。

# Controller
package MyApp::Controller::Foo;
use Mojo::Base 'Mojolicious::Controller', -signatures;

# Action
sub welcome ($self) {
  # Render response
  $self->render(text => 'Hello there.');
}

1;

所有路由都按照定义的顺序进行匹配,一旦找到合适的路由,匹配就停止。因此,我们可以通过首先声明最常访问的路由来提高路由性能。路由缓存也将被自动使用,以更优雅地处理突发的流量峰值。

标签