Plack :: Builder - 最后一行没有使用mount - 错误消息

时间:2013-05-27 16:02:23

标签: perl plack

拥有下一个简单的Plack应用程序:

use strict;
use warnings;
use Plack::Builder;

my $app = sub { 
        return [ 200, [ 'Content-Type' => 'text/plain' ], [ 'Hello World' ] ]; 
};

builder {
    foreach my $act ( qw( /some/aa /another/bb  / ) ) {
        mount $act => $app;
    }
};

返回错误:

WARNING: You used mount() in a builder block, but the last line (app) isn't using mount().
WARNING: This causes all mount() mappings to be ignored.
 at /private/tmp/test.psgi line 13.
Error while loading /private/tmp/test.psgi: to_app() is called without mount(). No application to build. at /private/tmp/test.psgi line 13.

但下一个构建器块没问题。

builder {
    foreach my $act ( qw( /some/aa /another/bb  / ) ) {
        mount $act => $app;
    }
    mount "/" => $app;
};

我理解的比Plack::Builder manual说的

  

注意:在构建器代码中使用mount后,必须使用mount   对于所有路径,包括根路径(/)。

但是在for循环中,我将/挂载作为最后一个:qw( /some/aa /another/bb / ),因此场景背后的某些内容

有人可以解释一下吗?

1 个答案:

答案 0 :(得分:4)

查看source code有助于了解正在发生的事情:

sub builder(&) {
    my $block = shift;
    ...
    my $app = $block->();

    if ($mount_is_called) {
        if ($app ne $urlmap) {
            Carp::carp("WARNING: You used mount() in a builder block,

因此,builder只是一个子程序,它的参数是一个代码块。将对该代码块进行评估,结果将在$app中结束。但是,使用您的代码,评估结果是空字符串,它来自终止foreach循环:

$ perl -MData::Dumper -e 'sub test{ for("a", "b"){ $_ } }; print Dumper(test())'
$VAR1 = '';

由于mount foo => $bar是“正义”的句法糖,在你的情况下甚至难以阅读,我建议你向裸金属迈出一小步,跳过句法糖并直接使用Plack::App::URLMap

use strict;
use warnings;
use Plack::App::URLMap;

my $app = sub { 
    return [ 200, [ 'Content-Type' => 'text/plain' ], [ 'Hello World' ] ]; 
};

my $map = Plack::App::URLMap->new;

foreach my $act ( qw( /some/aa /another/bb  / ) ) {
    $map->mount( $act => $app );
}

$map->to_app;