1Mojolicious::Guides::RoUusteirngC(o3n)tributed Perl DocuMmoejnotlaitciioonus::Guides::Routing(3)
2
3
4

NAME

6       Mojolicious::Guides::Routing - Routing requests
7

OVERVIEW

9       This document contains a simple and fun introduction to the Mojolicious
10       router and its underlying concepts.
11

CONCEPTS

13       Essentials every Mojolicious developer should know.
14
15   Dispatcher
16       The foundation of every web framework is a tiny black box connecting
17       incoming requests with code generating the appropriate response.
18
19         GET /user/show/1 -> $c->render(text => 'Daniel');
20
21       This black box is usually called a dispatcher. There are many
22       implementations using different strategies to establish these
23       connections, but pretty much all are based around mapping the path part
24       of the request URL to some kind of response generator.
25
26         /user/show/2 -> $c->render(text => 'Isabell');
27         /user/show/3 -> $c->render(text => 'Sara');
28         /user/show/4 -> $c->render(text => 'Stefan');
29         /user/show/5 -> $c->render(text => 'Fynn');
30
31       While it is very well possible to make all these connections static, it
32       is also rather inefficient. That's why regular expressions are commonly
33       used to make the dispatch process more dynamic.
34
35         qr!/user/show/(\d+)! -> $c->render(text => $users{$1});
36
37       Modern dispatchers have pretty much everything HTTP has to offer at
38       their disposal and can use many more variables than just the request
39       path, such as request method and headers like "Host", "User-Agent" and
40       "Accept".
41
42         GET /user/show/23 HTTP/1.1
43         Host: mojolicious.org
44         User-Agent: Mojolicious (Perl)
45         Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
46
47   Routes
48       While regular expressions are quite powerful they also tend to be
49       unpleasant to look at and are generally overkill for ordinary path
50       matching.
51
52         qr!/user/admin/(\d+)! -> $c->render(text => $users{$1});
53
54       This is where routes come into play, they have been designed from the
55       ground up to represent paths with placeholders.
56
57         /user/admin/:id -> $c->render(text => $users{$id});
58
59       The only difference between a static path and the route above is the
60       ":id" placeholder. One or more placeholders can be anywhere in the
61       route.
62
63         /user/:role/:id
64
65       A fundamental concept of the Mojolicious router is that extracted
66       placeholder values are turned into a hash.
67
68         /user/admin/23 -> /user/:role/:id -> {role => 'admin', id => 23}
69
70       This hash is basically the center of every Mojolicious application, you
71       will learn more about this later on.  Internally, routes get compiled
72       to regular expressions, so you can get the best of both worlds with a
73       little bit of experience.
74
75         /user/admin/:id -> qr/(?-xism:^\/user\/admin\/([^\/.]+))/
76
77       A trailing slash in the path is always optional.
78
79         /user/admin/23/ -> /user/:role/:id -> {role => 'admin', id => 23}
80
81   Reversibility
82       One more huge advantage routes have over regular expressions is that
83       they are easily reversible, extracted placeholders can be turned back
84       into a path at any time.
85
86         /sebastian -> /:name -> {name => 'sebastian'}
87         {name => 'sebastian'} -> /:name -> /sebastian
88
89       Every placeholder has a name, even if it's just an empty string.
90
91   Standard placeholders
92       Standard placeholders are the simplest form of placeholders, they use a
93       colon prefix and match all characters except "/" and ".", similar to
94       the regular expression "([^/.]+)".
95
96         /hello              -> /:name/hello -> undef
97         /sebastian/23/hello -> /:name/hello -> undef
98         /sebastian.23/hello -> /:name/hello -> undef
99         /sebastian/hello    -> /:name/hello -> {name => 'sebastian'}
100         /sebastian23/hello  -> /:name/hello -> {name => 'sebastian23'}
101         /sebastian 23/hello -> /:name/hello -> {name => 'sebastian 23'}
102
103       All placeholders can be surrounded by "<" and ">" to separate them from
104       the surrounding text.
105
106         /hello             -> /<:name>hello -> undef
107         /sebastian/23hello -> /<:name>hello -> undef
108         /sebastian.23hello -> /<:name>hello -> undef
109         /sebastianhello    -> /<:name>hello -> {name => 'sebastian'}
110         /sebastian23hello  -> /<:name>hello -> {name => 'sebastian23'}
111         /sebastian 23hello -> /<:name>hello -> {name => 'sebastian 23'}
112
113       The colon prefix is optional for standard placeholders that are
114       surrounded by "<" and ">".
115
116         /i♥mojolicious -> /<one>♥<two> -> {one => 'i', two => 'mojolicious'}
117
118   Relaxed placeholders
119       Relaxed placeholders are just like standard placeholders, but use a
120       hash prefix and match all characters except "/", similar to the regular
121       expression "([^/]+)".
122
123         /hello              -> /#name/hello -> undef
124         /sebastian/23/hello -> /#name/hello -> undef
125         /sebastian.23/hello -> /#name/hello -> {name => 'sebastian.23'}
126         /sebastian/hello    -> /#name/hello -> {name => 'sebastian'}
127         /sebastian23/hello  -> /#name/hello -> {name => 'sebastian23'}
128         /sebastian 23/hello -> /#name/hello -> {name => 'sebastian 23'}
129
130       They can be especially useful for manually matching file names with
131       extensions, rather than using format detection.
132
133         /music/song.mp3 -> /music/#filename -> {filename => 'song.mp3'}
134
135   Wildcard placeholders
136       Wildcard placeholders are just like the two types of placeholders
137       above, but use an asterisk prefix and match absolutely everything,
138       including "/" and ".", similar to the regular expression "(.+)".
139
140         /hello              -> /*name/hello -> undef
141         /sebastian/23/hello -> /*name/hello -> {name => 'sebastian/23'}
142         /sebastian.23/hello -> /*name/hello -> {name => 'sebastian.23'}
143         /sebastian/hello    -> /*name/hello -> {name => 'sebastian'}
144         /sebastian23/hello  -> /*name/hello -> {name => 'sebastian23'}
145         /sebastian 23/hello -> /*name/hello -> {name => 'sebastian 23'}
146
147       They can be useful for manually matching entire file paths.
148
149         /music/rock/song.mp3 -> /music/*filepath -> {filepath => 'rock/song.mp3'}
150

BASICS

152       Most commonly used features every Mojolicious developer should know
153       about.
154
155   Minimal route
156       The attribute "routes" in Mojolicious contains a router you can use to
157       generate route structures.
158
159         # Application
160         package MyApp;
161         use Mojo::Base 'Mojolicious', -signatures;
162
163         sub startup ($self) {
164           # Router
165           my $r = $self->routes;
166
167           # Route
168           $r->get('/welcome')->to(controller => 'foo', action => 'welcome');
169         }
170
171         1;
172
173       The minimal route above will load and instantiate the class
174       "MyApp::Controller::Foo" and call its "welcome" method.  Routes are
175       usually configured in the "startup" method of the application class,
176       but the router can be accessed from everywhere (even at runtime).
177
178         # Controller
179         package MyApp::Controller::Foo;
180         use Mojo::Base 'Mojolicious::Controller', -signatures;
181
182         # Action
183         sub welcome ($self) {
184           # Render response
185           $self->render(text => 'Hello there.');
186         }
187
188         1;
189
190       All routes match in the same order in which they were defined, and
191       matching stops as soon as a suitable route has been found. So you can
192       improve the routing performance by declaring your most frequently
193       accessed routes first. A routing cache will also be used automatically
194       to handle sudden traffic spikes more gracefully.
195
196   Routing destination
197       After you start a new route with methods like "get" in
198       Mojolicious::Routes::Route, you can also give it a destination in the
199       form of a hash using the chained method "to" in
200       Mojolicious::Routes::Route.
201
202         # /welcome -> {controller => 'foo', action => 'welcome'}
203         $r->get('/welcome')->to(controller => 'foo', action => 'welcome');
204
205       Now if the route matches an incoming request it will use the content of
206       this hash to try and find appropriate code to generate a response.
207
208   HTTP methods
209       There are already shortcuts for the most common HTTP request methods
210       like "post" in Mojolicious::Routes::Route, and for more control "any"
211       in Mojolicious::Routes::Route accepts an optional array reference with
212       arbitrary request methods as first argument.
213
214         # PUT /hello  -> undef
215         # GET /hello  -> {controller => 'foo', action => 'hello'}
216         $r->get('/hello')->to(controller => 'foo', action => 'hello');
217
218         # PUT /hello -> {controller => 'foo', action => 'hello'}
219         $r->put('/hello')->to(controller => 'foo', action => 'hello');
220
221         # POST /hello -> {controller => 'foo', action => 'hello'}
222         $r->post('/hello')->to(controller => 'foo', action => 'hello');
223
224         # GET|POST /bye  -> {controller => 'foo', action => 'bye'}
225         $r->any(['GET', 'POST'] => '/bye')->to(controller => 'foo', action => 'bye');
226
227         # * /whatever -> {controller => 'foo', action => 'whatever'}
228         $r->any('/whatever')->to(controller => 'foo', action => 'whatever');
229
230       There is one small exception, "HEAD" requests are considered equal to
231       "GET", but content will not be sent with the response even if it is
232       present.
233
234         # GET /test  -> {controller => 'bar', action => 'test'}
235         # HEAD /test -> {controller => 'bar', action => 'test'}
236         $r->get('/test')->to(controller => 'bar', action => 'test');
237
238       You can also use the "_method" query parameter to override the request
239       method. This can be very useful when submitting forms with browsers
240       that only support "GET" and "POST".
241
242         # PUT  /stuff             -> {controller => 'baz', action => 'stuff'}
243         # POST /stuff?_method=PUT -> {controller => 'baz', action => 'stuff'}
244         $r->put('/stuff')->to(controller => 'baz', action => 'stuff');
245
246   IRIs
247       IRIs are handled transparently, that means paths are guaranteed to be
248       unescaped and decoded from bytes to characters.
249
250         # GET /☃ (Unicode snowman) -> {controller => 'foo', action => 'snowman'}
251         $r->get('/☃')->to(controller => 'foo', action => 'snowman');
252
253   Stash
254       The generated hash of a matching route is actually the center of the
255       whole Mojolicious request cycle. We call it the stash, and it persists
256       until a response has been generated.
257
258         # /bye -> {controller => 'foo', action => 'bye', mymessage => 'Bye'}
259         $r->get('/bye')->to(controller => 'foo', action => 'bye', mymessage => 'Bye');
260
261       There are a few stash values with special meaning, such as "controller"
262       and "action", but you can generally fill it with whatever data you need
263       to generate a response. Once dispatched the whole stash content can be
264       changed at any time.
265
266         sub bye ($self) {
267
268           # Get message from stash
269           my $msg = $self->stash('mymessage');
270
271           # Change message in stash
272           $self->stash(mymessage => 'Welcome');
273         }
274
275       You can use "defaults" in Mojolicious to set default stash values that
276       will be available everywhere in the application.
277
278         $app->defaults(mymessage => 'Howdy');
279
280       For a full list of reserved stash values see "stash" in
281       Mojolicious::Controller.
282
283   Nested routes
284       It is also possible to build tree structures from routes to remove
285       repetitive code. A route with children can't match on its own though,
286       only the actual endpoints of these nested routes can.
287
288         # /foo     -> undef
289         # /foo/bar -> {controller => 'foo', action => 'bar'}
290         my $foo = $r->any('/foo')->to(controller => 'foo');
291         $foo->get('/bar')->to(action => 'bar');
292
293       The stash is simply inherited from route to route and newer values
294       override old ones.
295
296         # /cats      -> {controller => 'cats', action => 'index'}
297         # /cats/nyan -> {controller => 'cats', action => 'nyan'}
298         # /cats/lol  -> {controller => 'cats', action => 'default'}
299         my $cats = $r->any('/cats')->to(controller => 'cats', action => 'default');
300         $cats->get('/')->to(action => 'index');
301         $cats->get('/nyan')->to(action => 'nyan');
302         $cats->get('/lol');
303
304       With a few common prefixes you can also greatly improve the routing
305       performance of applications with many routes, because children are only
306       tried if the prefix matched first.
307
308   Special stash values
309       When the dispatcher sees "controller" and "action" values in the stash
310       it will always try to turn them into a class and method to dispatch to.
311       The "controller" value gets converted from "snake_case" to "CamelCase"
312       using "camelize" in Mojo::Util and appended to one or more namespaces,
313       defaulting to a controller namespace based on the application class
314       ("MyApp::Controller"), as well as the bare application class ("MyApp"),
315       and these namespaces are searched in that order. The action value is
316       not changed at all, so both values are case-sensitive.
317
318         # Application
319         package MyApp;
320         use Mojo::Base 'Mojolicious', -signatures;
321
322         sub startup ($self) {
323           # /bye -> MyApp::Controller::Foo->bye
324           $self->routes->get('/bye')->to(controller => 'foo', action => 'bye');
325         }
326
327         1;
328
329         # Controller
330         package MyApp::Controller::Foo;
331         use Mojo::Base 'Mojolicious::Controller', -signatures;
332
333         # Action
334         sub bye ($self) {
335           # Render response
336           $self->render(text => 'Good bye.');
337         }
338
339         1;
340
341       Controller classes are perfect for organizing code in larger projects.
342       There are more dispatch strategies, but because controllers are the
343       most commonly used ones they also got a special shortcut in the form of
344       "controller#action".
345
346         # /bye -> {controller => 'foo', action => 'bye', mymessage => 'Bye'}
347         $r->get('/bye')->to('foo#bye', mymessage => 'Bye');
348
349       During camelization "-" characters get replaced with "::", this allows
350       multi-level "controller" hierarchies.
351
352         # / -> MyApp::Controller::Foo::Bar->hi
353         $r->get('/')->to('foo-bar#hi');
354
355       You can also just specify the "controller" in CamelCase form instead of
356       snake_case.
357
358         # / -> MyApp::Controller::Foo::Bar->hi
359         $r->get('/')->to('Foo::Bar#hi');
360
361       For security reasons the dispatcher will always check if the
362       "controller" is actually a subclass of Mojolicious::Controller or Mojo
363       before dispatching to it.
364
365   Namespaces
366       You can use the "namespace" stash value to change the namespace of a
367       whole route with all its children.
368
369         # /bye -> MyApp::MyController::Foo::Bar->bye
370         $r->get('/bye')->to(namespace => 'MyApp::MyController', controller => 'Foo::Bar', action => 'bye');
371
372       The "controller" is always converted from "snake_case" to "CamelCase"
373       with "camelize" in Mojo::Util, and then appended to this "namespace".
374
375         # /bye -> MyApp::MyController::Foo::Bar->bye
376         $r->get('/bye')->to('foo-bar#bye', namespace => 'MyApp::MyController');
377
378         # /hey -> MyApp::MyController::Foo::Bar->hey
379         $r->get('/hey')->to('Foo::Bar#hey', namespace => 'MyApp::MyController');
380
381       You can also change the default namespaces for all routes in the
382       application with the router attribute "namespaces" in
383       Mojolicious::Routes, which usually defaults to a namespace based on the
384       application class ("MyApp::Controller"), as well as the bare
385       application class ("MyApp").
386
387         $r->namespaces(['MyApp::MyController']);
388
389   Route to callback
390       The "cb" stash value, which won't be inherited by nested routes, can be
391       used to bypass controllers and execute a callback instead.
392
393         $r->get('/bye')->to(cb => sub ($c) {
394           $c->render(text => 'Good bye.');
395         });
396
397       But just like in Mojolicious::Lite you can also pass the callback
398       directly, which usually looks much better.
399
400         $r->get('/bye' => sub ($c) {
401           $c->render(text => 'Good bye.');
402         });
403
404   Named routes
405       Naming your routes will allow backreferencing in many methods and
406       helpers throughout the whole framework, most of which internally rely
407       on "url_for" in Mojolicious::Controller for this.
408
409         # /foo/marcus -> {controller => 'foo', action => 'bar', user => 'marcus'}
410         $r->get('/foo/:user')->to('foo#bar')->name('baz');
411
412         # Generate URL "/foo/marcus" for route "baz" (in previous request context)
413         my $url = $c->url_for('baz');
414
415         # Generate URL "/foo/jan" for route "baz"
416         my $url = $c->url_for('baz', user => 'jan');
417
418         # Generate URL "http://127.0.0.1:3000/foo/jan" for route "baz"
419         my $url = $c->url_for('baz', user => 'jan')->to_abs;
420
421       You can assign a name with "name" in Mojolicious::Routes::Route, or let
422       the router generate one automatically, which would be equal to the
423       route itself without non-word characters, custom names have a higher
424       precedence though.
425
426         # /foo/bar ("foobar")
427         $r->get('/foo/bar')->to('test#stuff');
428
429         # Generate URL "/foo/bar"
430         my $url = $c->url_for('foobar');
431
432       To refer to the current route you can use the reserved name "current"
433       or no name at all.
434
435         # Generate URL for current route
436         my $url = $c->url_for('current');
437         my $url = $c->url_for;
438
439       To check or get the name of the current route you can use the helper
440       "current_route" in Mojolicious::Plugin::DefaultHelpers.
441
442         # Name for current route
443         my $name = $c->current_route;
444
445         # Check route name in code shared by multiple routes
446         $c->stash(button => 'green') if $c->current_route('login');
447
448   Optional placeholders
449       Extracted placeholder values will simply redefine older stash values if
450       they already exist.
451
452         # /bye -> {controller => 'foo', action => 'bar', mymessage => 'bye'}
453         # /hey -> {controller => 'foo', action => 'bar', mymessage => 'hey'}
454         $r->get('/:mymessage')->to('foo#bar', mymessage => 'hi');
455
456       One more interesting effect, a placeholder automatically becomes
457       optional if there is already a stash value of the same name present,
458       this works similar to the regular expression "([^/.]+)?".
459
460         # / -> {controller => 'foo', action => 'bar', mymessage => 'hi'}
461         $r->get('/:mymessage')->to('foo#bar', mymessage => 'hi');
462
463         # /test/123     -> {controller => 'foo', action => 'bar', mymessage => 'hi'}
464         # /test/bye/123 -> {controller => 'foo', action => 'bar', mymessage => 'bye'}
465         $r->get('/test/:mymessage/123')->to('foo#bar', mymessage => 'hi');
466
467       And if two optional placeholders are only separated by a slash, that
468       slash can become optional as well.
469
470   Restrictive placeholders
471       A very easy way to make placeholders more restrictive are alternatives,
472       you just make a list of possible values, which then work similar to the
473       regular expression "(bender|leela)".
474
475         # /fry    -> undef
476         # /bender -> {controller => 'foo', action => 'bar', name => 'bender'}
477         # /leela  -> {controller => 'foo', action => 'bar', name => 'leela'}
478         $r->get('/:name' => [name => ['bender', 'leela']])->to('foo#bar');
479
480       You can also adjust the regular expressions behind placeholders
481       directly, just make sure not to use "^" and "$" or capturing groups
482       "(...)", because placeholders become part of a larger regular
483       expression internally, non-capturing groups "(?:...)" are fine though.
484
485         # /23   -> {controller => 'foo', action => 'bar', number => 23}
486         # /test -> undef
487         $r->get('/:number' => [number => qr/\d+/])->to('foo#bar');
488
489         # /23   -> undef
490         # /test -> {controller => 'foo', action => 'bar', name => 'test'}
491         $r->get('/:name' => [name => qr/[a-zA-Z]+/])->to('foo#bar');
492
493       This way you get easily readable routes and the raw power of regular
494       expressions.
495
496   Placeholder types
497       And if you have multiple routes using restrictive placeholders you can
498       also turn them into placeholder types with "add_type" in
499       Mojolicious::Routes.
500
501         # A type with alternatives
502         $r->add_type(futurama_name => ['bender', 'leela']);
503
504         # /fry    -> undef
505         # /bender -> {controller => 'foo', action => 'bar', name => 'bender'}
506         # /leela  -> {controller => 'foo', action => 'bar', name => 'leela'}
507         $r->get('/<name:futurama_name>')->to('foo#bar');
508
509       Placeholder types work just like restrictive placeholders, they are
510       just reusable with the "<placeholder:type>" notation.
511
512         # A type adjusting the regular expression
513         $r->add_type(upper => qr/[A-Z]+/);
514
515         # /user/ROOT -> {controller => 'users', action => 'show', name => 'ROOT'}
516         # /user/root -> undef
517         # /user/23   -> undef
518         $r->get('/user/<name:upper>')->to('users#show');
519
520       Some types like "num" are used so commonly that they are available by
521       default.
522
523         # /article/12   -> {controller => 'article', action => 'show', id => 12}
524         # /article/test -> undef
525         $r->get('/article/<id:num>')->to('articles#show');
526
527       For a full list of available placeholder types see also "TYPES" in
528       Mojolicious::Routes.
529
530   Introspection
531       The command Mojolicious::Command::routes can be used from the command
532       line to list all available routes together with names and underlying
533       regular expressions.
534
535         $ ./myapp.pl routes -v
536         /foo/:name  ....  POST  fooname  ^/foo/([^/.]+)/?(?:\.([^/]+))?$
537         /bar        ..U.  *     bar      ^/bar
538           +/baz     ...W  GET   baz      ^/baz/?(?:\.([^/]+))?$
539         /yada       ....  *     yada     ^/yada/?(?:\.([^/]+))?$
540
541   Under
542       To share code with multiple nested routes you can use "under" in
543       Mojolicious::Routes::Route, because unlike normal nested routes, the
544       routes generated with it have their own intermediate destination and
545       result in additional dispatch cycles when they match.
546
547         # /foo     -> undef
548         # /foo/bar -> {controller => 'foo', action => 'baz'}
549         #             {controller => 'foo', action => 'bar'}
550         my $foo = $r->under('/foo')->to('foo#baz');
551         $foo->get('/bar')->to('#bar');
552
553       The actual action code for this destination needs to return a true
554       value or the dispatch chain will be broken, this can be a very powerful
555       tool for authentication.
556
557         # /blackjack -> {cb => sub {...}}
558         #               {controller => 'hideout', action => 'blackjack'}
559         my $auth = $r->under('/' => sub ($c) {
560
561           # Authenticated
562           return 1 if $c->req->headers->header('X-Bender');
563
564           # Not authenticated
565           $c->render(text => "You're not Bender.", status => 401);
566           return undef;
567         });
568         $auth->get('/blackjack')->to('hideout#blackjack');
569
570       Broken dispatch chains can be continued by calling "continue" in
571       Mojolicious::Controller, this allows for example, non-blocking
572       operations to finish before reaching the next dispatch cycle.
573
574         my $maybe = $r->under('/maybe' => sub ($c) {
575
576           # Wait 3 seconds and then give visitors a 50% chance to continue
577           Mojo::IOLoop->timer(3 => sub {
578
579             # Loser
580             return $c->render(text => 'No luck.') unless int rand 2;
581
582             # Winner
583             $c->continue;
584           });
585
586           return undef;
587         });
588         $maybe->get('/')->to('maybe#winner');
589
590       Every destination is just a snapshot of the stash at the time the route
591       matched, and only the "format" value is shared by all of them. For a
592       little more power you can introspect the preceding and succeeding
593       destinations with "match" in Mojolicious::Controller.
594
595         # Action of the fourth dispatch cycle
596         my $action = $c->match->stack->[3]{action};
597
598   Formats
599       File extensions like ".html" and ".txt" at the end of a route can be
600       detected and stored in the stash value "format".  Use a restrictive
601       placeholder to declare the possible values.
602
603         # /foo.txt -> undef
604         # /foo.rss -> {controller => 'foo', action => 'bar', format => 'rss'}
605         # /foo.xml -> {controller => 'foo', action => 'bar', format => 'xml'}
606         $r->get('/foo' => [format => ['rss', 'xml']])->to('foo#bar');
607
608       This for example, allows multiple templates in different formats to
609       share the same action code. And just like with placeholders you can use
610       a default value to make the format optional.
611
612         # /foo      -> {controller => 'foo', action => 'bar'}
613         # /foo.html -> {controller => 'foo', action => 'bar', format => 'html'}
614         # /foo.txt  -> {controller => 'foo', action => 'bar', format => 'txt'}
615         $r->get('/foo' => [format => ['html', 'txt']])->to('foo#bar', format => undef);
616
617       Formats can be inherited by nested routes.
618
619         # /foo      -> {controller => 'foo', action => 'one', format => undef}
620         # /foo.html -> {controller => 'foo', action => 'one', format => 'html'}
621         # /foo.json -> {controller => 'foo', action => 'one', format => 'json'}
622         # /bar      -> {controller => 'bar', action => 'two', format => undef}
623         # /bar.html -> {controller => 'bar', action => 'two', format => 'html'}
624         # /bar.json -> {controller => 'bar', action => 'two', format => 'json'}
625         my $with_format = $r->any('/' => [format => ['html', 'json']])->to(format => undef);
626         $with_format->get('/foo')->to('foo#one');
627         $with_format->get('/bar')->to('bar#two');
628
629       A "format" value can also be passed to "url_for" in
630       Mojolicious::Controller.
631
632         # /foo/23.txt -> {controller => 'foo', action => 'bar', id => 23, format => 'txt'}
633         $r->get('/foo/:id')->to('foo#bar')->name('baz');
634
635         # Generate URL "/foo/24.txt" for route "baz"
636         my $url = $c->url_for('baz', id => 24, format => 'txt');
637
638   WebSockets
639       With the method "websocket" in Mojolicious::Routes::Route you can
640       restrict access to WebSocket handshakes, which are normal "GET"
641       requests with some additional information.
642
643         # /echo (WebSocket handshake)
644         $r->websocket('/echo')->to('foo#echo');
645
646         # Controller
647         package MyApp::Controller::Foo;
648         use Mojo::Base 'Mojolicious::Controller', -signatures;
649
650         # Action
651         sub echo ($self) {
652           $self->on(message => sub ($self, $msg) {
653             $self->send("echo: $msg");
654           });
655         }
656
657         1;
658
659       The connection gets established when you respond to the WebSocket
660       handshake request with a 101 response status, which happens
661       automatically if you subscribe to an event with "on" in
662       Mojolicious::Controller or send a message with "send" in
663       Mojolicious::Controller right away.
664
665         GET /echo HTTP/1.1
666         Host: mojolicious.org
667         User-Agent: Mojolicious (Perl)
668         Connection: Upgrade
669         Upgrade: websocket
670         Sec-WebSocket-Key: IDM3ODE4NDk2MjA1OTcxOQ==
671         Sec-WebSocket-Version: 13
672
673         HTTP/1.1 101 Switching Protocols
674         Server: Mojolicious (Perl)
675         Date: Tue, 03 Feb 2015 17:08:24 GMT
676         Connection: Upgrade
677         Upgrade: websocket
678         Sec-WebSocket-Accept: SWsp5N2iNxPbHlcOTIw8ERvyVPY=
679
680   Catch-all route
681       Since routes match in the order in which they were defined, you can
682       catch all requests that did not match in your last route with an
683       optional wildcard placeholder.
684
685         # * /*
686         $r->any('/*whatever' => {whatever => ''} => sub ($c) {
687           my $whatever = $c->param('whatever');
688           $c->render(text => "/$whatever did not match.", status => 404);
689         });
690
691   Conditions
692       Conditions such as "headers", "agent" and "host" from
693       Mojolicious::Plugin::HeaderCondition can be applied to any route with
694       the method "requires" in Mojolicious::Routes::Route, and allow even
695       more powerful route constructs.
696
697         # / (Origin: http://perl.org)
698         $r->get('/')->requires(headers => {Origin => qr/perl\.org/})->to('foo#bar');
699
700         # / (Firefox)
701         $r->get('/')->requires(agent => qr/Firefox/)->to('browser-test#firefox');
702
703         # / (Internet Explorer)
704         $r->get('/')->requires(agent => qr/Internet Explorer/)->to('browser-test#ie');
705
706         # http://docs.mojolicious.org/Mojolicious
707         $r->get('/')->requires(host => 'docs.mojolicious.org')->to('perldoc#index');
708
709       Just be aware that conditions are too complex for the routing cache,
710       which normally speeds up recurring requests, and can therefore reduce
711       performance.
712
713   Hooks
714       Hooks operate outside the routing system and allow you to extend the
715       framework itself by sharing code with all requests indiscriminately
716       through "hook" in Mojolicious, which makes them a very powerful tool
717       especially for plugins.
718
719         # Application
720         package MyApp;
721         use Mojo::Base 'Mojolicious', -signatures;
722
723         sub startup ($self) {
724
725           # Check all requests for a "/test" prefix
726           $self->hook(before_dispatch => sub ($c) {
727             $c->render(text => 'This request did not reach the router.') if $c->req->url->path->contains('/test');
728           });
729
730           # These will not be reached if the hook above renders a response
731           my $r = $self->routes;
732           $r->get('/welcome')->to('foo#welcome');
733           $r->post('/bye')->to('foo#bye');
734         }
735
736         1;
737
738       Post-processing the response to add or remove headers is a very common
739       use.
740
741         # Make sure static files are cached
742         $app->hook(after_static => sub ($c) {
743           $c->res->headers->cache_control('max-age=3600, must-revalidate');
744         });
745
746         # Remove a default header
747         $app->hook(after_dispatch => sub ($c) {
748           $c->res->headers->remove('Server');
749         });
750
751       Same for pre-processing the request.
752
753         # Choose template variant based on request headers
754         $app->hook(before_dispatch => sub ($c) {
755           return unless my $agent = $c->req->headers->user_agent;
756           $c->stash(variant => 'ie') if $agent =~ /Internet Explorer/;
757         });
758
759       Or more advanced extensions to add monitoring to your application.
760
761         # Forward exceptions to a web service
762         $app->hook(after_dispatch => sub ($c) {
763           return unless my $e = $c->stash('exception');
764           $c->ua->post('https://example.com/bugs' => form => {exception => $e});
765         });
766
767       You can even extend much of the core functionality.
768
769         # Make controller object available to actions as $_
770         $app->hook(around_action => sub ($next, $c, $action, $last) {
771           local $_ = $c;
772           return $next->();
773         });
774
775         # Pass route name as argument to actions
776         $app->hook(around_action => sub ($next, $c, $action, $last) {
777           return $c->$action($c->current_route);
778         });
779
780       For a full list of available hooks see "HOOKS" in Mojolicious.
781

ADVANCED

783       Less commonly used and more powerful features.
784
785   Shortcuts
786       To make route generation more expressive, you can also add your own
787       shortcuts with "add_shortcut" in Mojolicious::Routes.
788
789         # Simple "resource" shortcut
790         $r->add_shortcut(resource => sub ($r, $name) {
791
792           # Prefix for resource
793           my $resource = $r->any("/$name")->to("$name#");
794
795           # Render a list of resources
796           $resource->get('/')->to('#index')->name($name);
797
798           # Render a form to create a new resource (submitted to "store")
799           $resource->get('/create')->to('#create')->name("create_$name");
800
801           # Store newly created resource (submitted by "create")
802           $resource->post->to('#store')->name("store_$name");
803
804           # Render a specific resource
805           $resource->get('/:id')->to('#show')->name("show_$name");
806
807           # Render a form to edit a resource (submitted to "update")
808           $resource->get('/:id/edit')->to('#edit')->name("edit_$name");
809
810           # Store updated resource (submitted by "edit")
811           $resource->put('/:id')->to('#update')->name("update_$name");
812
813           # Remove a resource
814           $resource->delete('/:id')->to('#remove')->name("remove_$name");
815
816           return $resource;
817         });
818
819         # GET /users         -> {controller => 'users', action => 'index'}
820         # GET /users/create  -> {controller => 'users', action => 'create'}
821         # POST /users        -> {controller => 'users', action => 'store'}
822         # GET /users/23      -> {controller => 'users', action => 'show', id => 23}
823         # GET /users/23/edit -> {controller => 'users', action => 'edit', id => 23}
824         # PUT /users/23      -> {controller => 'users', action => 'update', id => 23}
825         # DELETE /users/23   -> {controller => 'users', action => 'remove', id => 23}
826         $r->resource('users');
827
828   Rearranging routes
829       From application startup until the first request has arrived, all
830       routes can still be moved around or even removed with methods like
831       "add_child" in Mojolicious::Routes::Route and "remove" in
832       Mojolicious::Routes::Route.
833
834         # GET /example/show -> {controller => 'example', action => 'show'}
835         my $show = $r->get('/show')->to('example#show');
836         $r->any('/example')->add_child($show);
837
838         # Nothing
839         $r->get('/secrets/show')->to('secrets#show')->name('show_secrets');
840         $r->find('show_secrets')->remove;
841
842       Especially for rearranging routes created by plugins this can be very
843       useful, to find routes by their name you can use "find" in
844       Mojolicious::Routes::Route.
845
846         # GET /example/test -> {controller => 'example', action => 'test'}
847         $r->get('/something/else')->to('something#else')->name('test');
848         my $test = $r->find('test');
849         $test->pattern->parse('/example/test');
850         $test->pattern->defaults({controller => 'example', action => 'test'});
851
852       Even the route pattern and destination can still be changed with
853       "parse" in Mojolicious::Routes::Pattern and "defaults" in
854       Mojolicious::Routes::Pattern.
855
856   Adding conditions
857       You can also add your own conditions with the method "add_condition" in
858       Mojolicious::Routes. All conditions are basically router plugins that
859       run every time a new request arrives, and which need to return a true
860       value for the route to match.
861
862         # A condition that randomly allows a route to match
863         $r->add_condition(random => sub ($route, $c, $captures, $num) {
864
865           # Loser
866           return undef if int rand $num;
867
868           # Winner
869           return 1;
870         });
871
872         # /maybe (25% chance)
873         $r->get('/maybe')->requires(random => 4)->to('foo#bar');
874
875       Use whatever request information you need.
876
877         # A condition to check query parameters (useful for mock web services)
878         $r->add_condition(query => sub ($route, $c, $captures, $hash) {
879
880           for my $key (keys %$hash) {
881             my $param = $c->req->url->query->param($key);
882             return undef unless defined $param && $param eq $hash->{$key};
883           }
884
885           return 1;
886         });
887
888         # /hello?to=world&test=1
889         $r->get('/hello')->requires(query => {test => 1, to => 'world'})->to('foo#bar');
890
891   Condition plugins
892       You can also package your conditions as reusable plugins.
893
894         # Plugin
895         package Mojolicious::Plugin::WerewolfCondition;
896         use Mojo::Base 'Mojolicious::Plugin', -signatures;
897
898         use Astro::MoonPhase;
899
900         sub register ($self, $app, $conf) {
901
902           # Add "werewolf" condition
903           $app->routes->add_condition(werewolf => sub ($route, $c, $captures, $days) {
904
905             # Keep the werewolves out!
906             return undef if abs(14 - (phase(time))[2]) > ($days / 2);
907
908             # It's ok, no werewolf
909             return 1;
910           });
911         }
912
913         1;
914
915       Now just load the plugin and you are ready to use the condition in all
916       your applications.
917
918         # Application
919         package MyApp;
920         use Mojo::Base 'Mojolicious', -signatures;
921
922         sub startup ($self) {
923
924           # Plugin
925           $self->plugin('WerewolfCondition');
926
927           # /hideout (keep them out for 4 days after full moon)
928           $self->routes->get('/hideout')->requires(werewolf => 4)->to(controller => 'foo', action => 'bar');
929         }
930
931         1;
932
933   Mount applications
934       The easiest way to embed one application into another is
935       Mojolicious::Plugin::Mount, which allows you to mount whole self-
936       contained applications under a domain and/or prefix.
937
938         use Mojolicious::Lite -signatures;
939
940         # Whole application mounted under "/prefix"
941         plugin Mount => {'/prefix' => '/home/sri/myapp/script/myapp'};
942
943         # Mount application with subdomain
944         plugin Mount => {'test.example.com' => '/home/sri/myapp2.pl'};
945
946         # Normal route
947         get '/' => sub ($c) {
948           $c->render(text => 'Hello World!');
949         };
950
951         app->start;
952
953   Embed applications
954       For a little more power you can also embed applications by using them
955       instead of a controller. This allows for example, the use of the
956       Mojolicious::Lite domain specific language in normal Mojolicious
957       controllers.
958
959         # Controller
960         package MyApp::Controller::Bar;
961         use Mojolicious::Lite -signatures;
962
963         # /hello
964         get '/hello' => sub ($c) {
965           my $name = $c->param('name');
966           $c->render(text => "Hello $name.");
967         };
968
969         1;
970
971       With the attribute "partial" in Mojolicious::Routes::Route, you can
972       allow the route to partially match and use only the remaining path in
973       the embedded application, the base path will be passed along in the
974       "path" stash value.
975
976         # /foo/*
977         $r->any('/foo')->partial(1)->to('bar#', name => 'Mojo');
978
979       A minimal embeddable application is nothing more than a subclass of
980       Mojolicious, containing a "handler" method accepting
981       Mojolicious::Controller objects.
982
983         package MyApp::Controller::Bar;
984         use Mojo::Base 'Mojolicious', -signatures;
985
986         sub handler ($self, $c) {
987           $c->res->code(200);
988           my $name = $c->param('name');
989           $c->res->body("Hello $name.");
990         }
991
992         1;
993
994       The host application will only share very little information with the
995       embedded application through the stash. So you cannot currently use
996       route placeholders in routes leading to embedded applications, since
997       that would cause problems with "url_for" in Mojolicious::Controller.
998
999   Application plugins
1000       You can even package applications as self-contained reusable plugins.
1001
1002         # Plugin
1003         package Mojolicious::Plugin::MyEmbeddedApp;
1004         use Mojo::Base 'Mojolicious::Plugin', -signatures;
1005
1006         sub register ($self, $app, $conf) {
1007
1008           # Automatically add route
1009           $app->routes->any('/foo')->partial(1)->to(app => EmbeddedApp::app());
1010         }
1011
1012         package EmbeddedApp;
1013         use Mojolicious::Lite;
1014
1015         get '/bar' => 'bar';
1016
1017         1;
1018         __DATA__
1019         @@ bar.html.ep
1020         Hello World!
1021
1022       The "app" stash value, which won't be inherited by nested routes, can
1023       be used for already instantiated applications.  Now just load the
1024       plugin and you're done.
1025
1026         # Application
1027         package MyApp;
1028         use Mojo::Base 'Mojolicious', -signatures;
1029
1030         sub startup ($self) {
1031
1032           # Plugin
1033           $self->plugin('MyEmbeddedApp');
1034         }
1035
1036         1;
1037

MORE

1039       You can continue with Mojolicious::Guides now or take a look at the
1040       Mojolicious wiki <https://github.com/mojolicious/mojo/wiki>, which
1041       contains a lot more documentation and examples by many different
1042       authors.
1043

SUPPORT

1045       If you have any questions the documentation might not yet answer, don't
1046       hesitate to ask in the Forum <https://forum.mojolicious.org>, on Matrix
1047       <https://matrix.to/#/#mojo:matrix.org>, or IRC
1048       <https://web.libera.chat/#mojo>.
1049
1050
1051
1052perl v5.38.0                      2023-09-11   Mojolicious::Guides::Routing(3)
Impressum