| 1 | package Mojolicious::Plugin::Mount; | ||
| 2 | use Mojo::Base 'Mojolicious::Plugin'; | ||
| 3 | |||
| 4 | use Mojo::Server; | ||
| 5 | |||
| 6 | sub register { | ||
| 7 | my ($self, $app, $conf) = @_; | ||
| 8 | |||
| 9 | my $path = (keys %$conf)[0]; | ||
| 10 | my $embed = Mojo::Server->new->load_app($conf->{$path})->secrets($app->secrets)->log($app->log); | ||
| 11 | |||
| 12 | # Extract host | ||
| 13 | my $host; | ||
| 14 | ($host, $path) = ($1 ? qr/^(?:.*\.)?\Q$2\E$/i : qr/^\Q$2\E$/i, $3) if $path =~ m!^(\*\.)?([^/]+)(/.*)?$!; | ||
| 15 | |||
| 16 | my $route = $app->routes->any($path)->partial(1)->to(app => $embed); | ||
| 17 | return $host ? $route->requires(host => $host) : $route; | ||
| 18 | } | ||
| 19 | |||
| 20 | 1; | ||
| 21 | |||
| 22 | =encoding utf8 | ||
| 23 | |||
| 24 | =head1 NAME | ||
| 25 | |||
| 26 | Mojolicious::Plugin::Mount - Application mount plugin | ||
| 27 | |||
| 28 | =head1 SYNOPSIS | ||
| 29 | |||
| 30 | # Mojolicious | ||
| 31 | my $route = $app->plugin(Mount => {'/prefix' => '/home/sri/foo/script/foo'}); | ||
| 32 | |||
| 33 | # Mojolicious::Lite | ||
| 34 | my $route = plugin Mount => {'/prefix' => '/home/sri/myapp.pl'}; | ||
| 35 | |||
| 36 | # Adjust the generated route and mounted application | ||
| 37 | my $example = plugin Mount => {'/example' => '/home/sri/example.pl'}; | ||
| 38 | $example->to(message => 'It works great!'); | ||
| 39 | my $app = $example->pattern->defaults->{app}; | ||
| 40 | $app->config(foo => 'bar'); | ||
| 41 | $app->log(app->log); | ||
| 42 | |||
| 43 | # Mount application with host | ||
| 44 | plugin Mount => {'example.com' => '/home/sri/myapp.pl'}; | ||
| 45 | |||
| 46 | # Host and path | ||
| 47 | plugin Mount => {'example.com/myapp' => '/home/sri/myapp.pl'}; | ||
| 48 | |||
| 49 | # Or even hosts with wildcard subdomains | ||
| 50 | plugin Mount => {'*.example.com/myapp' => '/home/sri/myapp.pl'}; | ||
| 51 | |||
| 52 | =head1 DESCRIPTION | ||
| 53 | |||
| 54 | L<Mojolicious::Plugin::Mount> is a plugin that allows you to mount whole L<Mojolicious> applications. | ||
| 55 | |||
| 56 | The code of this plugin is a good example for learning to build new plugins, you're welcome to fork it. | ||
| 57 | |||
| 58 | See L<Mojolicious::Plugins/"PLUGINS"> for a list of plugins that are available by default. | ||
| 59 | |||
| 60 | =head1 METHODS | ||
| 61 | |||
| 62 | L<Mojolicious::Plugin::Mount> inherits all methods from L<Mojolicious::Plugin> and implements the following new ones. | ||
| 63 | |||
| 64 | =head2 register | ||
| 65 | |||
| 66 | my $route = $plugin->register(Mojolicious->new, {'/foo' => '/some/app.pl'}); | ||
| 67 | |||
| 68 | Mount L<Mojolicious> application and return the generated route, which is usually a L<Mojolicious::Routes::Route> | ||
| 69 | object. | ||
| 70 | |||
| 71 | =head1 SEE ALSO | ||
| 72 | |||
| 73 | L<Mojolicious>, L<Mojolicious::Guides>, L<https://mojolicious.org>. | ||
| 74 | |||
| 75 | =cut |