在 Plack::Builder 中安装 "hosts"

Mount "hosts" in Plack::Builder

Plack::Builder and also this answer 的概要说:

# in .psgi
use Plack::Builder;

my $app = sub { ... };

builder {
    mount "/foo" => builder {
        enable "Foo";
        $app;
    };

    mount "/bar" => $app2;
    mount "http://example.com/" => builder { $app3 };
};

我尝试了以下方法:

use Plack::Builder;
my $app1 = sub { return [200, ['Content-Type' => 'text/plain'], [ "Hello 1"] ]; };
my $app2 = sub { return [200, ['Content-Type' => 'text/plain'], [ "Hello 2"] ]; };
my $app3 = sub { return [200, ['Content-Type' => 'text/plain'], [ "Hello 3"] ]; };

builder {
        mount "/a1" => builder { $app1 };
        mount "http://myhost.com" => builder{ $app2 };
        mount "/" => builder{ $app3 };
}

但是当尝试 运行 它与 plackup 得到:

Error while loading /tmp/app.psgi: Paths need to start with / at /home/cw/.anyenv/envs/plenv/versions/5.20.3/lib/perl5/site_perl/5.20.3/Plack/Builder.pm line 108.

怎么了?

我没有在文档中明确提到这一点,但除了主机名之外,您还必须包含路径组件,例如http://myhost.com/foo。变化

mount "http://myhost.com" => builder{ $app2 };

mount "http://myhost.com/" => builder{ $app2 };

(即主机 myhost.com 上的 /

相关代码在Plack::App::URLMapmount只是调用了Plack::App::URLMap的map方法):

if ($location =~ m!^https?://(.*?)(/.*)!) {
    $host     = ;
    $location = ;
}