perlplackpsgi

Mount "hosts" in Plack::Builder


The Synopsis for the Plack::Builder and also this answer says:

# in .psgi
use Plack::Builder;

my $app = sub { ... };

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

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

I tried the following:

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 };
}

But when tried to run it with plackup got:

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.

What is wrong?


Solution

  • I don't see this mentioned explicitly in the documentation, but you have to include a path component in addition to the hostname, e.g. http://myhost.com/foo. Change

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

    to

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

    (i.e. / on host myhost.com)

    The relevant code is in Plack::App::URLMap (mount simply calls Plack::App::URLMap's map method):

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