
=encoding utf8

=head1 NAME

Mojolicious::Guides::Routing - Routing

=head1 OVERVIEW

This document contains a simple and fun introduction to the L<Mojolicious>
router and its underlying concepts.

=head1 CONCEPTS

Essentials every L<Mojolicious> developer should know.

=head2 Dispatcher

The foundation of every web framework is a tiny black box connecting incoming
requests with code generating the appropriate response.

  GET /user/show/1 -> $self->render(text => 'Sebastian!');

This black box is usually called a dispatcher.
There are many implementations using different strategies to establish these
connections, but pretty much all are based around mapping the requests path
to some kind of response generator.

  /user/show/1 -> $self->render(text => 'Sebastian!');
  /user/show/2 -> $self->render(text => 'Sara!');
  /user/show/3 -> $self->render(text => 'Baerbel!');
  /user/show/4 -> $self->render(text => 'Wolfgang!');

While it is very well possible to make all these connections static, it is
also rather inefficient.
That's why regular expressions are commonly used to make the dispatch process
more dynamic.

  qr|/user/show/(\d+)| -> $self->render(text => $users{$1});

Modern dispatchers have pretty much everything HTTP has to offer at their
disposal and can use many more variables than just the request path, such as
request method and headers like C<Host>, C<User-Agent> and C<Accept>.

  GET /user/show/23 HTTP/1.1
  Host: mojolicio.us
  User-Agent: Mozilla/5.0 (compatible; Mojolicious; Perl)
  Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8

=head2 Routes

While regular expressions are quite powerful they also tend to be unpleasant
to look at and are generally overkill for ordinary path matching.

  qr|/user/show/(\d+)| -> $self->render(text => $users{$1});

This is where routes come into play, they have been designed from the ground
up to represent paths with placeholders.

  /user/show/:id -> $self->render(text => $users{$id});

The only difference between a static path and the route above is the C<:id>
placeholder.
One or more placeholders can be anywhere in the route.

  /user/:action/:id

A fundamental concept of the L<Mojolicious> router is that extracted
placeholder values are turned into a hash.

  /user/show/23 -> /user/:action/:id -> {action => 'show', id => 23}

This hash is basically the center of every L<Mojolicious> application, you
will learn more about this later on.
Internally routes get compiled to regular expressions, so you can get the
best of both worlds with a little bit of experience.

  /user/show/:id -> qr/(?-xism:^\/user\/show/([^\/\.]+))/

A trailing slash is always optional.

  /user/show/23/ -> /user/:action/:id -> {action => 'show', id => 23}

=head2 Reversibility

One more huge advantage routes have over regular expressions is that they are
easily reversible, extracted placeholders can be turned back into a path at
any time.

  /sebastian -> /:name -> {name => 'sebastian'}
  {name => 'sebastian'} -> /:name -> /sebastian

=head2 Generic Placeholders

Generic placeholders are the simplest form of placeholders and match
all characters except C</> and C<.>.

  /hello              -> /:name/hello -> undef
  /sebastian/23/hello -> /:name/hello -> undef
  /sebastian.23/hello -> /:name/hello -> undef
  /sebastian/hello    -> /:name/hello -> {name => 'sebastian'}
  /sebastian23/hello  -> /:name/hello -> {name => 'sebastian23'}
  /sebastian 23/hello -> /:name/hello -> {name => 'sebastian 23'}

A generic placeholder can be surrounded by brackets to separate it from the
surrounding text.

  /hello             -> /(:name)hello -> undef
  /sebastian/23hello -> /(:name)hello -> undef
  /sebastian.23hello -> /(:name)hello -> undef
  /sebastianhello    -> /(:name)hello -> {name => 'sebastian'}
  /sebastian23hello  -> /(:name)hello -> {name => 'sebastian23'}
  /sebastian 23hello -> /(:name)hello -> {name => 'sebastian 23'}

=head2 Wildcard Placeholders

Wildcard placeholders are just like generic placeholders, but match
absolutely everything.

  /hello              -> /*name/hello -> undef
  /sebastian/23/hello -> /*name/hello -> {name => 'sebastian/23'}
  /sebastian.23/hello -> /*name/hello -> {name => 'sebastian.23'}
  /sebastian/hello    -> /*name/hello -> {name => 'sebastian'}
  /sebastian23/hello  -> /*name/hello -> {name => 'sebastian23'}
  /sebastian 23/hello -> /*name/hello -> {name => 'sebastian 23'}

=head2 Relaxed Placeholders

Relaxed placeholders are similar to the two placeholders above, but always
require brackets and match all characters except C</>.

  /hello              -> /(.name)/hello -> undef
  /sebastian/23/hello -> /(.name)/hello -> undef
  /sebastian.23/hello -> /(.name)/hello -> {name => 'sebastian.23'}
  /sebastian/hello    -> /(.name)/hello -> {name => 'sebastian'}
  /sebastian23/hello  -> /(.name)/hello -> {name => 'sebastian23'}
  /sebastian 23/hello -> /(.name)/hello -> {name => 'sebastian 23'}

=head1 BASICS

Most commonly used features every L<Mojolicious> developer should know about.

=head2 Minimal Route

Every L<Mojolicious> application has a router object you can use to generate
routes structures.

  # Application
  package MyApp;
  use Mojo::Base 'Mojolicious';

  sub startup {
    my $self = shift;

    # Router
    my $r = $self->routes;

    # Route
    $r->route('/welcome')->to(controller => 'foo', action => 'welcome');
  }

  1;

The minimal static route above will load and instantiate the class
C<MyApp::Foo> and call its C<welcome> method.

  # Controller
  package MyApp::Foo;
  use Mojo::Base 'Mojolicious::Controller';

  # Action
  sub welcome {
    my $self = shift;

    # Render response
    $self->render(text => 'Hello there!');
  }

  1;

Routes are usually configured in the C<startup> method of the application
class, but the router can be accessed from everywhere (even at runtime).

=head2 Routing Destination

After you start a new route with the C<route> method you can also give it a
destination in the form of a hash using the chained C<to> method.

  # /welcome -> {controller => 'foo', action => 'welcome'}
  $r->route('/welcome')->to(controller => 'foo', action => 'welcome');

Now if the route matches an incoming request it will use the content of this
hash to try and find appropriate code to generate a response.

=head2 Stash

The generated hash of a matching route is actually the center of the whole
L<Mojolicious> request cycle.
We call it the stash, and it is basically a global namespace that persists
until a response has been generated.

  # /bye -> {controller => 'foo', action => 'bye', mymessage => 'Bye!'}
  $r->route('/bye')
    ->to(controller => 'foo', action => 'bye', mymessage => 'Bye!');

There are a few stash values with special meaning, such as C<controller> and
C<action>, but you can generally fill it with whatever data you need to
generate a response.
Once dispatched the whole stash content can be changed at any time.

  sub bye {
    my $self = shift;

    # Get message from stash
    my $message = $self->stash('mymessage');

    # Change message in stash
    $self->stash(mymessage => 'Welcome!');
  }

=head2 Special Stash Values (C<controller> and C<action>)

When the dispatcher sees C<controller> and C<action> values in the stash it
will always try to turn them into a class and method to dispatch to.
The C<controller> value gets camelized and prefixed with a C<namespace>
(defaulting to the applications class) while the action value is not changed
at all, because of this both values are case sensitive.

  # Application
  package MyApp;
  use Mojo::Base 'Mojolicious';

  sub startup {
    my $self = shift;

    # Router
    my $r = $self->routes;

    # /bye -> {controller => 'foo', action => 'bye'} -> MyApp::Foo->bye
    $r->route('/bye')->to(controller => 'foo', action => 'bye');
  }

  1;

  # Controller
  package MyApp::Foo;
  use Mojo::Base 'Mojolicious::Controller';

  # Action
  sub bye {
    my $self = shift;

    # Render response
    $self->render(text => 'Good bye!');
  }

  1;

Controller classes are perfect for organizing code in larger projects.
There are more dispatch strategies, but because controllers are the most
commonly used ones they also got a special shortcut in the form of
C<controller#action>.

  # /bye -> {controller => 'foo', action => 'bye', mymessage => 'Bye!'}
  $r->route('/bye')->to('foo#bye', mymessage => 'Bye!');

During camelization C<-> gets replaced with C<::>, this allows multi level
C<controller> hierarchies.

  # / -> {controller => 'foo-bar', action => 'hi'} -> MyApp::Foo::Bar->hi
  $r->route('/')->to('foo-bar#hi');

=head2 Route To Class (C<namespace>)

From time to time you might want to dispatch to a whole different C<namespace>.

  # /bye -> MyApp::Controller::Foo->bye
  $r->route('/bye')
    ->to(namespace => 'MyApp::Controller::Foo', action => 'bye');

The C<controller> is always appended to the C<namespace> if available.

  # /bye -> MyApp::Controller::Foo->bye
  $r->route('/bye')->to('foo#bye', namespace => 'MyApp::Controller');

You can also change the default namespace for all routes in the application.

  $r->namespace('MyApp::Controller');

=head2 Route To Callback (C<cb>)

You can use the C<cb> stash value to bypass controllers and execute a
callback instead.

  $r->route('/bye')->to(cb => sub {
    my $self = shift;
    $self->render(text => 'Good bye!');
  });

This technique is the foundation of L<Mojolicious::Lite>, you can learn more
about it from the included tutorial.

=head2 More Restrictive Placeholders

A very easy way to make placeholders more restrictive are alternatives, you
just make a list of possible values.

  # /bender -> {controller => 'foo', action => 'bar', name => 'bender'}
  # /leela  -> {controller => 'foo', action => 'bar', name => 'leela'}
  # /fry    -> undef
  $r->route('/:name', name => [qw/bender leela/])
    ->to(controller => 'foo', action => 'bar');

You can also adjust the regular expressions behind placeholders to better
suit your needs.
Just make sure not to use C<^> and C<$> or capturing groups C<(...)>, because
placeholders become part of a larger regular expression internally,
C<(?:...)> is fine though.

  # /23   -> {controller => 'foo', action => 'bar', number => 23}
  # /test -> undef
  $r->route('/:number', number => qr/\d+/)
    ->to(controller => 'foo', action => 'bar');

  # /23   -> undef
  # /test -> {controller => 'foo', action => 'bar', name => 'test'}
  $r->route('/:name', name => qr/[a-zA-Z]+/)
    ->to(controller => 'foo', action => 'bar');

This way you get easily readable routes and the raw power of regular
expressions.

=head2 Formats

File extensions like C<.html> and C<.txt> at the end of a route are
automatically detected and stored in the stash value C<format>.

  # /foo      -> {controller => 'foo', action => 'bar'}
  # /foo.html -> {controller => 'foo', action => 'bar', format => 'html'}
  # /foo.txt  -> {controller => 'foo', action => 'bar', format => 'txt'}
  $r->route('/foo')->to(controller => 'foo', action => 'bar');

This for example allows multiple templates for different formats to share the
same code.
You can also mention a format in the route pattern to only match one, just
make sure the more specific routes go first.

  # /foo.txt -> {controller => 'foo', action => 'text', format => 'txt'}
  $r->route('/foo.txt')->to(controller => 'foo', action => 'text');

  # /foo      -> {controller => 'foo', action => 'hyper'}
  # /foo.html -> {controller => 'foo', action => 'hyper', format => 'html'}
  $r->route('/foo')->to(controller => 'foo', action => 'hyper');

Restrictive placeholders can also be used for format detection.

  # /foo.rss -> {controller => 'foo', action => 'feed', format => 'rss'}
  # /foo.xml -> {controller => 'foo', action => 'feed', format => 'xml'}
  # /foo.txt -> undef
  $r->route('/foo', format => [qw/rss xml/])
    ->to(controller => 'foo', action => 'feed');

Or you can just disable format detection.

  # /foo      -> {controller => 'foo', action => 'bar'}
  # /foo.html -> undef
  $r->route('/foo', format => 0)->to(controller => 'foo', action => 'bar');

=head2 Placeholders And Destinations

Extracted placeholder values will simply redefine older stash values if they
already exist.

  # /bye -> {controller => 'foo', action => 'bar', mymessage => 'bye'}
  # /hey -> {controller => 'foo', action => 'bar', mymessage => 'hey'}
  $r->route('/:mymessage')
    ->to(controller => 'foo', action => 'bar', mymessage => 'hi');

One more interesting effect, if a placeholder is at the end of a route and
there is already a stash value of the same name present, it automatically
becomes optional.

  # / -> {controller => 'foo', action => 'bar', mymessage => 'hi'}
  $r->route('/:mymessage')
    ->to(controller => 'foo', action => 'bar', mymessage => 'hi');

This is also the case if multiple placeholders are right after another and
not separated by other characters than C</>.

  # /           -> {controller => 'foo',   action => 'bar'}
  # /users      -> {controller => 'users', action => 'bar'}
  # /users/list -> {controller => 'users', action => 'list'}
  $r->route('/:controller/:action')
    ->to(controller => 'foo', action => 'bar');

Special stash values like C<controller> and C<action> can also be
placeholders, this allows for extremely flexible routes constructs.

=head2 Named Routes

Naming your routes will allow backreferencing in many kinds of helpers
throughout the whole framework.

  # /foo/abc -> {controller => 'foo', action => 'bar', name => 'abc'}
  $r->route('/foo/:name')->name('test')
    ->to(controller => 'foo', action => 'bar');

  # Generate URL "/foo/abc" for route "test"
  $self->url_for('test');

  # Generate URL "/foo/sebastian" for route "test"
  $self->url_for('test', name => 'sebastian');

Nameless routes get an automatically generated one assigned that is simply
equal to the route itself without non-word characters.

  # /foo/bar ("foobar")
  $r->route('/foo/bar')->to('test#stuff');

  # Generate URL "/foo/bar"
  $self->url_for('foobar');

To refer to the current route you can always use the reserved name
C<current>.

  # Generate URL for current route
  $self->url_for('current');

=head2 HTTP Methods

The C<via> method of the route object allows only specific HTTP methods to
pass.

  # GET /bye    -> {controller => 'foo', action => 'bye'}
  # POST /bye   -> undef
  # DELETE /bye -> undef
  $r->route('/bye')->via('get')->to(controller => 'foo', action => 'bye');

  # GET /bye    -> {controller => 'foo', action => 'bye'}
  # POST /bye   -> {controller => 'foo', action => 'bye'}
  # DELETE /bye -> undef
  $r->route('/bye')->via(qw/get post/)
    ->to(controller => 'foo', action => 'bye');

=head2 Nested Routes

It is also possible to build tree structures from routes to remove repetitive
code.
A route with children can't match on it's own though, only the actual
endpoints of these nested routes can.

  # /foo     -> undef
  # /foo/bar -> {controller => 'foo', action => 'bar'}
  my $foo = $r->route('/foo')->to(controller => 'foo');
  $foo->route('/bar')->to(action => 'bar');

The stash will simply move from route to route and newer values override old
ones.

  # /foo     -> undef
  # /foo/abc -> undef
  # /foo/bar -> {controller => 'foo', action => 'bar'}
  # /foo/baz -> {controller => 'foo', action => 'baz'}
  # /foo/cde -> {controller => 'foo', action => 'abc'}
  my $foo = $r->route('/foo')->to(controller => 'foo', action => 'abc');
  $foo->route('/bar')->to(action => 'bar');
  $foo->route('/baz')->to(action => 'baz');
  $foo->route('/cde');

=head2 Mojolicious::Lite routes

L<Mojolicious::Lite> routes are in fact just a small convenience layer around
everything described above and also part of the normal router.

  # GET /foo -> {controller => 'foo', action => 'abc'}
  $r->get('/foo')->to(controller => 'foo', action => 'abc');

This makes the process of growing your L<Mojolicious::Lite> prototypes into
full L<Mojolicious> applications very straightforward.

  # POST /bar
  $r->post('/bar' => sub {
    my $self = shift;
    $self->render(text => 'Just like a Mojolicious::Lite action!');
  });

Even the more abstract concepts are available.

  # GET  /yada
  # POST /yada
  my $yada = $r->under('/yada');
  $yada->get(sub {
    my $self = shift;
    $self->render(text => 'Hello!');
  });
  $yada->post(sub {
    my $self = shift;
    $self->render(text => 'Go away!');
  });

=head1 ADVANCED

Less commonly used and more powerful features.

=head2 Waypoints

Waypoints are very similar to normal nested routes but can match even if they
have children.

  # /foo     -> {controller => 'foo', action => 'baz'}
  # /foo/bar -> {controller => 'foo', action => 'bar'}
  my $foo = $r->waypoint('/foo')->to(controller => 'foo', action => 'baz');
  $foo->route('/bar')->to(action => 'bar');

All children will be ignored if a waypoint matches.

=head2 Bridges

Bridges unlike nested routes and waypoints always match and result in
additional dispatch cycles.

  # /foo     -> undef
  # /foo/bar -> {controller => 'foo', action => 'baz'}
  #             {controller => 'foo', action => 'bar'}
  my $foo = $r->bridge('/foo')->to(controller => 'foo', action => 'baz');
  $foo->route('/bar')->to(action => 'bar');

The actual bridge code needs to return a true value or the dispatch chain
will be broken, this makes bridges a very powerful tool for authentication.

  # /foo     -> undef
  # /foo/bar -> {cb => sub {...}}
  #             {controller => 'foo', action => 'bar'}
  my $foo = $r->bridge('/foo')->to(cb => sub {
    my $self = shift;

    # Authenticated
    return 1 if $self->req->headers->header('X-Bender');

    # Not authenticated
    return;
  });
  $foo->route('/bar')->to(controller => 'foo', action => 'bar');

=head2 Shortcuts

You can also add your own shortcuts to make route generation more expressive.

  # Simple "resource" shortcut
  $r->add_shortcut(resource => sub {
    my ($r, $name) = @_;

    # Generate "/$name" route
    my $resource = $r->route("/$name")->to("$name#");

    # Handle POST requests
    $resource->post->to('#create')->name("create_$name");

    # Handle GET requests
    $resource->get->to('#show')->name("show_$name");

    return $resource;
  });

  # POST /user -> {controller => 'user', action => 'create'}
  # GET  /user -> {controller => 'user', action => 'show'}
  $r->resource('user');

Shortcuts can lead to anything, routes, bridges or maybe even both.
And watch out for quicksand!

=head2 Conditions

Sometimes you might need a little more power, for example to check the
C<User-Agent> header in multiple routes.
This is where conditions come into play, they are basically router plugins.

  # Simple "User-Agent" condition
  $r->add_condition(
    agent => sub {
      my ($r, $c, $captures, $pattern) = @_;

      # User supplied regular expression
      return unless $pattern && ref $pattern eq 'Regexp';

      # Match "User-Agent" header and return true on success
      my $agent = $c->req->headers->user_agent;
      return 1 if $agent && $agent =~ $pattern;

      # No success
      return;
    }
  );

  # /firefox_only (Firefox) -> {controller => 'foo', action => 'bar'}
  $r->route('/firefox_only')->over(agent => qr/Firefox/)
    ->to(controller => 'foo', action => 'bar');

The method C<add_condition> registers the new condition in the router while
C<over> actually applies it to the route.

=head2 Condition Plugins

You can also package your conditions as reusable plugins.

  # Plugin
  package Mojolicious::Plugin::WerewolfCondition;
  use Mojo::Base 'Mojolicious::Plugin';

  use Astro::MoonPhase;

  sub register {
    my ($self, $app) = @_;

    # Add "werewolf" condition
    $app->routes->add_condition(
      werewolf => sub {
        my ($r, $c, $captures, $days) = @_;

        # Keep the werewolfs out!
        return if abs(14 - (phase(time))[2]) > ($days / 2);

        # It's ok, no werewolf
        return 1;
      }
    );
  }

  1;

Now just load the plugin and you are ready to use the condition in all your
applications.

  # Application
  package MyApp;
  use Mojo::Base 'Mojolicious';

  sub startup {
    my $self = shift;

    # Plugin
    $self->plugin('werewolf_condition');

    # Routes
    my $r = $self->routes;

    # /hideout (keep them out for 4 days after full moon)
    $r->route('/hideout')->over(werewolf => 4)
      ->to(controller => 'foo', action => 'bar');
  }

  1;

=head2 Embedding Applications

You can easily embed whole applications simply by using them instead of a
controller.
This allows for example the use of the L<Mojolicious::Lite> domain specific
language in normal L<Mojolicious> controllers.

  # Controller
  package MyApp::Bar;
  use Mojolicious::Lite;

  # /hello
  get '/hello' => sub {
    my $self = shift;
    my $name = $self->param('name');
    $self->render(text => "Hello $name!");
  };

  1;

With the C<detour> method which is very similar to C<to>, you can allow the
route to partially match and use only the remaining path in the embedded
application.

  # /foo/*
  $r->route('/foo')->detour('bar#', name => 'Mojo');

A minimal embeddable application is nothing more than a subclass of L<Mojo>,
containing a C<handler> method accepting L<Mojolicious::Controller> objects.

  package MyApp::Bar;
  use Mojo::Base 'Mojo';

  sub handler {
    my ($self, $c) = @_;
    $c->res->code(200);
    my $name = $c->param('name');
    $c->res->body("Hello $name!");
  }

  1;

You can also just use L<Mojolicious::Plugin::Mount> to mount whole
self-contained applications under a prefix.

  use Mojolicious::Lite;

  # Whole application mounted under "/prefix"
  plugin mount => {'/prefix' => '/home/sri/myapp.pl'};

  # Normal route
  get '/' => sub { shift->render_text('Hello World!') };

  app->start;

=head2 Application Plugins

Embedding L<Mojolicious> applications is easy, but it gets even easier if you
package the whole thing as a self contained reusable plugin.

  # Plugin
  package Mojolicious::Plugin::MyEmbeddedApp;
  use Mojo::Base 'Mojolicious::Plugin';

  sub register {
    my ($self, $app) = @_;

    # Automatically add route
    $app->routes->route('/foo')->detour(app => EmbeddedApp::app());
  }

  package EmbeddedApp;
  use Mojolicious::Lite;

  get '/bar' => 'bar';

  1;
  __DATA__
  @@ bar.html.ep
  Hello World!

The C<app> stash value can be used for already instantiated applications.
Now just load the plugin and you're done.

  # Application
  package MyApp;
  use Mojo::Base 'Mojolicious';

  sub startup {
    my $self = shift;

    # Plugin
    $self->plugin('my_embedded_app');
  }

  1;

=head2 WebSockets

You can restrict access to WebSocket handshakes using the C<websocket> method.

  # /ws (WebSocket handshake)
  $r->websocket('/echo')->to(controller => 'foo', action => 'echo');

  # Controller
  package MyApp::Foo;
  use Mojo::Base 'Mojolicious::Controller';

  # Action
  sub echo {
    my $self = shift;
    $self->on_message(sub {
      my ($self, $message) = @_;
      $self->send_message("echo: $message");
    });
  }

  1;

=head2 IRIs

IRIs are handled transparently, that means paths are guaranteed to be
unescaped and decoded to Perl characters.

  use utf8;

  # /☃ (unicode snowman) -> {controller => 'foo', action => 'snowman'}
  $r->route('/☃')->to(controller => 'foo', action => 'snowman');

Just don't forget to use the L<utf8> pragma or you'll make the unicode
snowman very sad.

=head2 Introspection

The C<routes> command can be used from the command line to list all available
routes together with name and underlying regular expressions.

  % script/myapp routes
  /foo/:name        GET   fooname        (?-xism:^/foo/([^\/\.]+))
  /baz/*everything  POST  bazeverything  (?-xism:^/baz/(.+))
  /bar/(.test)      *     bartest        (?-xism:^/bar/([^\/]+))

=head1 MORE

You can continue with L<Mojolicious::Guides> now or take a look at the
Mojolicious wiki L<http://github.com/kraih/mojo/wiki>, which contains a lot
more documentation and examples by many different authors.

=cut
