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

ADVANCED

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

MORE

1034       You can continue with Mojolicious::Guides now or take a look at the
1035       Mojolicious wiki <https://github.com/mojolicious/mojo/wiki>, which
1036       contains a lot more documentation and examples by many different
1037       authors.
1038

SUPPORT

1040       If you have any questions the documentation might not yet answer, don't
1041       hesitate to ask in the Forum <https://forum.mojolicious.org>, on Matrix
1042       <https://matrix.to/#/#mojo:matrix.org>, or IRC
1043       <https://web.libera.chat/#mojo>.
1044
1045
1046
1047perl v5.36.0                      2022-07-22   Mojolicious::Guides::Routing(3)
Impressum