Plack::App::URLMap - Map multiple apps in different paths


Plack documentation Contained in the Plack distribution.

Index


Code Index:

NAME

Top

Plack::App::URLMap - Map multiple apps in different paths

SYNOPSIS

Top

  use Plack::App::URLMap;

  my $app1 = sub { ... };
  my $app2 = sub { ... };
  my $app3 = sub { ... };

  my $urlmap = Plack::App::URLMap->new;
  $urlmap->map("/" => $app1);
  $urlmap->map("/foo" => $app2);
  $urlmap->map("http://bar.example.com/" => $app3);

  my $app = $urlmap->to_app;

DESCRIPTION

Top

Plack::App::URLMap is a PSGI application that can dispatch multiple applications based on URL path and hostnames (a.k.a "virtual hosting") and takes care of rewriting SCRIPT_NAME and PATH_INFO (See "HOW THIS WORKS" for details). This module is inspired by Rack::URLMap.

METHODS

Top

map
  $urlmap->map("/foo" => $app);
  $urlmap->map("http://bar.example.com/" => $another_app);

Maps URL path or an absolute URL to a PSGI application. The match order is sorted by host name length and then path length.

URL paths need to match from the beginning and should match completely till the path separator (or the end of the path). For example, if you register the path /foo, it will match with the request /foo, /foo/ or /foo/bar but it won't match with /foox.

Mapping URL with host names is also possible, and in that case the URL mapping works like a virtual host.

Mappings will nest. If $app is already mapped to /baz it will match a request for /foo/baz but not /foo. See "HOW THIS WORKS" for more details.

mount

Alias for map.

to_app
  my $handler = $urlmap->to_app;

Returns the PSGI application code reference. Note that the Plack::App::URLMap object is callable (by overloading the code dereference), so returning the object itself as a PSGI application should also work.

DEBUGGING

Top

You can set the environment variable PLACK_URLMAP_DEBUG to see how this application matches with the incoming request host names and paths.

HOW THIS WORKS

Top

This application works by fixing SCRIPT_NAME and PATH_INFO before dispatching the incoming request to the relocated applications.

Say you have a Wiki application that takes /index and /page/* and makes a PSGI application $wiki_app out of it, using one of supported web frameworks, you can put the whole application under /wiki by:

  # MyWikiApp looks at PATH_INFO and handles /index and /page/*
  my $wiki_app = sub { MyWikiApp->run(@_) };

  use Plack::App::URLMap;
  my $app = Plack::App::URLMap->new;
  $app->mount("/wiki" => $wiki_app);

When a request comes in with PATH_INFO set to /wiki/page/foo, the URLMap application $app strips the /wiki part from PATH_INFO and appends that to SCRIPT_NAME.

That way, if the $app is mounted under the root (i.e. SCRIPT_NAME is "") with standalone web servers like Starman, SCRIPT_NAME is now locally set to /wiki and PATH_INFO is changed to /page/foo when $wiki_app gets called.

AUTHOR

Top

Tatsuhiko Miyagawa

SEE ALSO

Top

Plack::Builder


Plack documentation Contained in the Plack distribution.

package Plack::App::URLMap;
use strict;
use warnings;
use parent qw(Plack::Component);
use constant DEBUG => $ENV{PLACK_URLMAP_DEBUG};

use Carp ();

sub mount { shift->map(@_) }

sub map {
    my $self = shift;
    my($location, $app) = @_;

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

    if ($location !~ m!^/!) {
        Carp::croak("Paths need to start with /");
    }
    $location =~ s!/$!!;

    push @{$self->{_mapping}}, [ $host, $location, $app ];
}

sub prepare_app {
    my $self = shift;
    # sort by path length
    $self->{_sorted_mapping} = [
        map  { [ @{$_}[2..4] ] }
        sort { $b->[0] <=> $a->[0] || $b->[1] <=> $a->[1] }
        map  { [ ($_->[0] ? length $_->[0] : 0), length($_->[1]), @$_ ] } @{$self->{_mapping}},
    ];
}

sub call {
    my ($self, $env) = @_;

    my $path_info   = $env->{PATH_INFO};
    my $script_name = $env->{SCRIPT_NAME};

    my($http_host, $server_name) = @{$env}{qw( HTTP_HOST SERVER_NAME )};

    if ($http_host and my $port = $env->{SERVER_PORT}) {
        $http_host =~ s/:$port$//;
    }

    for my $map (@{ $self->{_sorted_mapping} }) {
        my($host, $location, $app) = @$map;
        my $path = $path_info; # copy
        no warnings 'uninitialized';
        DEBUG && warn "Matching request (Host=$http_host Path=$path) and the map (Host=$host Path=$location)\n";
        next unless not defined $host     or
                    $http_host   eq $host or
                    $server_name eq $host;
        next unless $location eq '' or $path =~ s!^\Q$location\E!!;
        next unless $path eq '' or $path =~ m!^/!;
        DEBUG && warn "-> Matched!\n";

        my $orig_path_info   = $env->{PATH_INFO};
        my $orig_script_name = $env->{SCRIPT_NAME};

        $env->{PATH_INFO}  = $path;
        $env->{SCRIPT_NAME} = $script_name . $location;
        return $self->response_cb($app->($env), sub {
            $env->{PATH_INFO} = $orig_path_info;
            $env->{SCRIPT_NAME} = $orig_script_name;
        });
    }

    DEBUG && warn "All matching failed.\n";

    return [404, [ 'Content-Type' => 'text/plain' ], [ "Not Found" ]];
}

1;

__END__