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.

但是下一个构建块是OK的。

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

我理解Plack::Builder手册说

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

但是在for循环中,我将/挂载为最后一个:qw( /some/aa /another/bb / ),所以这里有在场景后面

有人能解释一下吗?

查看源代码有助于理解发生了什么:

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;

相关内容

  • 没有找到相关文章

最新更新