1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484
|
=encoding utf8
=head1 NAME
Mojolicious::Guides::Cookbook - Cookbook
=head1 OVERVIEW
This document contains many fun recipes for cooking with L<Mojolicious>.
=head1 DEPLOYMENT
Getting L<Mojolicious> and L<Mojolicious::Lite> applications running on
different platforms. Note that many real-time web features are based on the
L<Mojo::IOLoop> event loop, and therefore require one of the built-in web
servers to be able to use them to their full potential.
=head2 Built-in web server
L<Mojolicious> contains a very portable non-blocking I/O HTTP and WebSocket
server with L<Mojo::Server::Daemon>. It is usually used during development and
in the construction of more advanced web servers, but is solid and fast enough
for small to mid sized applications.
$ ./script/myapp daemon
Server available at http://127.0.0.1:3000.
It is available to every application through the command
L<Mojolicious::Command::daemon>, which has many configuration options and is
known to work on every platform Perl works on with its single-process
architecture.
$ ./script/myapp daemon -h
...List of available options...
Another huge advantage is that it supports TLS and WebSockets out of the box,
a development certificate for testing purposes is built right in, so it just
works, but you can specify all listen locations supported by
L<Mojo::Server::Daemon/"listen">.
$ ./script/myapp daemon -l https://[::]:3000
Server available at https://[::]:3000.
On UNIX platforms you can also add preforking and switch to a multi-process
architecture with L<Mojolicious::Command::prefork>, to take advantage of
multiple CPU cores and copy-on-write.
$ ./script/myapp prefork
Server available at http://127.0.0.1:3000.
Since all built-in web servers are based on the L<Mojo::IOLoop> event loop,
they scale best with non-blocking operations. But if your application for some
reason needs to perform many blocking operations, you can improve performance
by increasing the number of worker processes and decreasing the number of
concurrent connections each worker is allowed to handle (often as low as
C<1>).
$ ./script/myapp prefork -m production -w 10 -c 1
Server available at http://127.0.0.1:3000.
Your application is preloaded in the manager process during startup, to run
code whenever a new worker process has been forked you can use
L<Mojo::IOLoop/"next_tick">.
use Mojolicious::Lite;
Mojo::IOLoop->next_tick(sub {
app->log->info("Worker $$ star...ALL GLORY TO THE HYPNOTOAD!");
});
get '/' => {text => 'Hello Wor...ALL GLORY TO THE HYPNOTOAD!'};
app->start;
=head2 Morbo
After reading the L<Mojolicious::Lite> tutorial, you should already be
familiar with L<Mojo::Server::Morbo>.
Mojo::Server::Morbo
+- Mojo::Server::Daemon
It is basically a restarter that forks a new L<Mojo::Server::Daemon> web
server whenever a file in your project changes, and should therefore only be
used during development.
$ morbo ./script/myapp
Server available at http://127.0.0.1:3000.
=head2 Hypnotoad
For bigger applications L<Mojolicious> contains the UNIX optimized preforking
web server L<Mojo::Server::Hypnotoad>, which can take advantage of multiple
CPU cores and copy-on-write to scale up to thousands of concurrent client
connections.
Mojo::Server::Hypnotoad
|- Mojo::Server::Daemon [1]
|- Mojo::Server::Daemon [2]
|- Mojo::Server::Daemon [3]
+- Mojo::Server::Daemon [4]
It is based on the L<Mojo::Server::Prefork> web server, which adds preforking
to L<Mojo::Server::Daemon>, but optimized specifically for production
environments out of the box.
$ hypnotoad ./script/myapp
Server available at http://127.0.0.1:8080.
It automatically sets the operating mode to C<production> and you can tweak
many configuration settings right from within your application with
L<Mojo/"config">, for a full list see L<Mojo::Server::Hypnotoad/"SETTINGS">.
use Mojolicious::Lite;
app->config(hypnotoad => {listen => ['http://*:80']});
get '/' => {text => 'Hello Wor...ALL GLORY TO THE HYPNOTOAD!'};
app->start;
Or just add a C<hypnotoad> section to your L<Mojolicious::Plugin::Config> or
L<Mojolicious::Plugin::JSONConfig> configuration file.
# myapp.conf
{
hypnotoad => {
listen => ['https://*:443?cert=/etc/server.crt&key=/etc/server.key'],
workers => 10
}
};
But one of its biggest advantages is the support for effortless zero downtime
software upgrades (hot deployment). That means you can upgrade L<Mojolicious>,
Perl or even system libraries at runtime without ever stopping the server or
losing a single incoming connection, just by running the command above again.
$ hypnotoad ./script/myapp
Starting hot deployment for Hypnotoad server 31841.
You might also want to enable proxy support if you're using Hypnotoad behind a
reverse proxy. This allows L<Mojolicious> to automatically pick up the
C<X-Forwarded-For> and C<X-Forwarded-Proto> headers.
# myapp.conf
{hypnotoad => {proxy => 1}};
=head2 Zero downtime software upgrades
Hypnotoad makes zero downtime software upgrades (hot deployment) very simple,
as you can see above, but on modern operating systems that support the
C<SO_REUSEPORT> socket option, there is also another method available that
works with all built-in web servers.
$ ./script/myapp prefork -P /tmp/first.pid -l http://*:8080?reuse=1
Server available at http://127.0.0.1:8080.
All you have to do is start a second web server listening to the same port and
stop the first web server gracefully afterwards.
$ ./script/myapp prefork -P /tmp/second.pid -l http://*:8080?reuse=1
Server available at http://127.0.0.1:8080.
$ kill -s TERM `cat /tmp/first.pid`
Just remember that both web servers need to be started with the C<reuse>
parameter.
=head2 Nginx
One of the most popular setups these days is Hypnotoad behind an
L<Nginx|http://nginx.org> reverse proxy, which even supports WebSockets in
newer versions.
upstream myapp {
server 127.0.0.1:8080;
}
server {
listen 80;
server_name localhost;
location / {
proxy_pass http://myapp;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto "http";
}
}
=head2 Apache/mod_proxy
Another good reverse proxy is L<Apache|http://httpd.apache.org> with
C<mod_proxy>, the configuration looks quite similar to the Nginx one above.
<VirtualHost *:80>
ServerName localhost
<Proxy *>
Order deny,allow
Allow from all
</Proxy>
ProxyRequests Off
ProxyPreserveHost On
ProxyPass / http://localhost:8080/ keepalive=On
ProxyPassReverse / http://localhost:8080/
RequestHeader set X-Forwarded-Proto "http"
</VirtualHost>
=head2 Apache/CGI
C<CGI> is supported out of the box and your L<Mojolicious> application will
automatically detect that it is executed as a C<CGI> script. It's use in
production environments is discouraged though, because as a result of how
C<CGI> works, it is very slow and many web servers are making it exceptionally
hard to configure properly.
ScriptAlias / /home/sri/myapp/script/myapp/
=head2 PSGI/Plack
L<PSGI> is an interface between Perl web frameworks and web servers, and
L<Plack> is a Perl module and toolkit that contains L<PSGI> middleware,
helpers and adapters to web servers. L<PSGI> and L<Plack> are inspired by
Python's WSGI and Ruby's Rack. L<Mojolicious> applications are ridiculously
simple to deploy with L<Plack>.
$ plackup ./script/myapp
L<Plack> provides many server and protocol adapters for you to choose from,
such as C<FCGI>, C<uWSGI> and C<mod_perl>.
$ plackup ./script/myapp -s FCGI -l /tmp/myapp.sock
The C<MOJO_REVERSE_PROXY> environment variable can be used to enable proxy
support, this allows L<Mojolicious> to automatically pick up the
C<X-Forwarded-For> and C<X-Forwarded-Proto> headers.
$ MOJO_REVERSE_PROXY=1 plackup ./script/myapp
If an older server adapter is unable to correctly detect the application home
directory, you can simply use the C<MOJO_HOME> environment variable.
$ MOJO_HOME=/home/sri/myapp plackup ./script/myapp
There is no need for a C<.psgi> file, just point the server adapter at your
application script, it will automatically act like one if it detects the
presence of a C<PLACK_ENV> environment variable.
=head2 Plack middleware
Wrapper scripts like C<myapp.fcgi> are a great way to separate deployment and
application logic.
#!/usr/bin/env plackup -s FCGI
use Plack::Builder;
builder {
enable 'Deflater';
require './script/myapp';
};
L<Mojo::Server::PSGI> can be used directly to load and customize applications
in the wrapper script.
#!/usr/bin/env plackup -s FCGI
use Mojo::Server::PSGI;
use Plack::Builder;
builder {
enable 'Deflater';
my $server = Mojo::Server::PSGI->new;
$server->load_app('./script/myapp');
$server->app->config(foo => 'bar');
$server->to_psgi_app;
};
But you could even use middleware right in your application.
use Mojolicious::Lite;
use Plack::Builder;
get '/welcome' => sub {
my $c = shift;
$c->render(text => 'Hello Mojo!');
};
builder {
enable 'Deflater';
app->start;
};
=head2 Rewriting
Sometimes you might have to deploy your application in a blackbox environment
where you can't just change the server configuration or behind a reverse proxy
that passes along additional information with C<X-*> headers. In such cases
you can use the hook L<Mojolicious/"before_dispatch"> to rewrite incoming
requests.
# Change scheme if "X-Forwarded-HTTPS" header is set
$app->hook(before_dispatch => sub {
my $c = shift;
$c->req->url->base->scheme('https')
if $c->req->headers->header('X-Forwarded-HTTPS');
});
Since reverse proxies generally don't pass along information about path
prefixes your application might be deployed under, rewriting the base path of
incoming requests is also quite common.
# Move first part and slash from path to base path in production mode
$app->hook(before_dispatch => sub {
my $c = shift;
push @{$c->req->url->base->path->trailing_slash(1)},
shift @{$c->req->url->path->leading_slash(0)};
}) if $app->mode eq 'production';
L<Mojo::URL> objects are very easy to manipulate, just make sure that the URL
(C<foo/bar?baz=yada>), which represents the routing destination, is always
relative to the base URL (C<http://example.com/myapp/>), which represents the
deployment location of your application.
=head2 Application embedding
From time to time you might want to reuse parts of L<Mojolicious> applications
like configuration files, database connection or helpers for other scripts,
with this little L<Mojo::Server> based mock server you can just embed them.
use Mojo::Server;
# Load application with mock server
my $server = Mojo::Server->new;
my $app = $server->load_app('./myapp.pl');
# Access fully initialized application
say for @{$app->static->paths};
say $app->config->{secret_identity};
say $app->dumper({just => 'a helper test'});
say $app->build_controller->render_to_string(template => 'foo');
The plugin L<Mojolicious::Plugin::Mount> uses this functionality to allow you
to combine multiple applications into one and deploy them together.
use Mojolicious::Lite;
plugin Mount => {'test1.example.com' => '/home/sri/myapp1.pl'};
plugin Mount => {'test2.example.com' => '/home/sri/myapp2.pl'};
app->start;
=head2 Web server embedding
You can also use L<Mojo::IOLoop/"one_tick"> to embed the built-in web server
L<Mojo::Server::Daemon> into alien environments like foreign event loops that
for some reason can't just be integrated with a new reactor backend.
use Mojolicious::Lite;
use Mojo::IOLoop;
use Mojo::Server::Daemon;
# Normal action
get '/' => {text => 'Hello World!'};
# Connect application with web server and start accepting connections
my $daemon
= Mojo::Server::Daemon->new(app => app, listen => ['http://*:8080']);
$daemon->start;
# Call "one_tick" repeatedly from the alien environment
Mojo::IOLoop->one_tick while 1;
=head1 REAL-TIME WEB
The real-time web is a collection of technologies that include Comet
(long polling), EventSource and WebSockets, which allow content to be pushed
to consumers with long-lived connections as soon as it is generated, instead
of relying on the more traditional pull model. All built-in web servers use
non-blocking I/O and are based on the L<Mojo::IOLoop> event loop, which
provides many very powerful features that allow real-time web applications to
scale up to thousands of concurrent client connections.
=head2 Backend web services
Since L<Mojo::UserAgent> is also based on the L<Mojo::IOLoop> event loop, it
won't block the built-in web servers when used non-blocking, even for high
latency backend web services.
use Mojolicious::Lite;
# Search MetaCPAN for "mojolicious"
get '/' => sub {
my $c = shift;
$c->ua->get('api.metacpan.org/v0/module/_search?q=mojolicious' => sub {
my ($ua, $tx) = @_;
$c->render('metacpan', hits => $tx->res->json->{hits}{hits});
});
};
app->start;
__DATA__
@@ metacpan.html.ep
<!DOCTYPE html>
<html>
<head><title>MetaCPAN results for "mojolicious"</title></head>
<body>
% for my $hit (@$hits) {
<p><%= $hit->{_source}{release} %></p>
% }
</body>
</html>
Multiple events such as concurrent requests can be easily synchronized with
L<Mojolicious::Plugin::DefaultHelpers/"delay">, which can help you avoid deep
nested closures and memory leaks that often result from continuation-passing
style.
use Mojolicious::Lite;
use Mojo::URL;
# Search MetaCPAN for "mojo" and "minion"
get '/' => sub {
my $c = shift;
# Prepare response in two steps
$c->delay(
# Concurrent requests
sub {
my $delay = shift;
my $url = Mojo::URL->new('api.metacpan.org/v0/module/_search');
$url->query({sort => 'date:desc'});
$c->ua->get($url->clone->query({q => 'mojo'}) => $delay->begin);
$c->ua->get($url->clone->query({q => 'minion'}) => $delay->begin);
},
# Delayed rendering
sub {
my ($delay, $mojo, $minion) = @_;
$c->render(json => {
mojo => $mojo->res->json('/hits/hits/0/_source/release'),
minion => $minion->res->json('/hits/hits/0/_source/release')
});
}
);
};
app->start;
=head2 Timers
Another primary feature of the event loop are timers, which are created with
L<Mojo::IOLoop/"timer"> and can for example be used to delay rendering of a
response, and unlike C<sleep>, won't block any other requests that might be
processed concurrently.
use Mojolicious::Lite;
use Mojo::IOLoop;
# Wait 3 seconds before rendering a response
get '/' => sub {
my $c = shift;
Mojo::IOLoop->timer(3 => sub {
$c->render(text => 'Delayed by 3 seconds!');
});
};
app->start;
Recurring timers created with L<Mojo::IOLoop/"recurring"> are slightly more
powerful, but need to be stopped manually, or they would just keep getting
emitted.
use Mojolicious::Lite;
use Mojo::IOLoop;
# Count to 5 in 1 second steps
get '/' => sub {
my $c = shift;
# Start recurring timer
my $i = 1;
my $id = Mojo::IOLoop->recurring(1 => sub {
$c->write_chunk($i);
$c->finish if $i++ == 5;
});
# Stop recurring timer
$c->on(finish => sub { Mojo::IOLoop->remove($id) });
};
app->start;
Timers are not tied to a specific request or connection, and can even be
created at startup time.
use Mojolicious::Lite;
use Mojo::IOLoop;
# Check title in the background every 10 seconds
my $title = 'Got no title yet.';
Mojo::IOLoop->recurring(10 => sub {
app->ua->get('http://mojolicio.us' => sub {
my ($ua, $tx) = @_;
$title = $tx->res->dom->at('title')->text;
});
});
# Show current title
get '/' => sub {
my $c = shift;
$c->render(json => {title => $title});
};
app->start;
Just remember that all events are processed cooperatively, so your callbacks
shouldn't block for too long.
=head2 Exceptions in events
Since timers and other non-blocking operations are running solely in the event
loop, outside of the application, exceptions that get thrown in callbacks
can't get caught and handled automatically. But you can handle them manually
by subscribing to the event L<Mojo::Reactor/"error"> or catching them inside
the callback.
use Mojolicious::Lite;
use Mojo::IOLoop;
# Forward error messages to the application log
Mojo::IOLoop->singleton->reactor->on(error => sub {
my ($reactor, $err) = @_;
app->log->error($err);
});
# Exception only gets logged (and connection times out)
get '/connection_times_out' => sub {
my $c = shift;
Mojo::IOLoop->timer(2 => sub {
die 'This request will not be getting a response';
});
};
# Exception gets caught and handled
get '/catch_exception' => sub {
my $c = shift;
Mojo::IOLoop->timer(2 => sub {
eval { die 'This request will be getting a response' };
$c->reply->exception($@) if $@;
});
};
app->start;
A default subscriber that turns all errors into warnings will usually be added
by L<Mojo::IOLoop> as a fallback.
Mojo::IOLoop->singleton->reactor->unsubscribe('error');
During development or for applications where crashing is simply preferable,
you can also make every exception that gets thrown in a callback fatal by
removing all of its subscribers.
=head2 WebSocket web service
The WebSocket protocol offers full bi-directional low-latency communication
channels between clients and servers. Receive messages just by subscribing to
events such as L<Mojo::Transaction::WebSocket/"message"> with the method
L<Mojolicious::Controller/"on"> and return them with
L<Mojolicious::Controller/"send">.
use Mojolicious::Lite;
# Template with browser-side code
get '/' => 'index';
# WebSocket echo service
websocket '/echo' => sub {
my $c = shift;
# Opened
$c->app->log->debug('WebSocket opened.');
# Increase inactivity timeout for connection a bit
$c->inactivity_timeout(300);
# Incoming message
$c->on(message => sub {
my ($c, $msg) = @_;
$c->send("echo: $msg");
});
# Closed
$c->on(finish => sub {
my ($c, $code, $reason) = @_;
$c->app->log->debug("WebSocket closed with status $code.");
});
};
app->start;
__DATA__
@@ index.html.ep
<!DOCTYPE html>
<html>
<head><title>Echo</title></head>
<body>
<script>
var ws = new WebSocket('<%= url_for('echo')->to_abs %>');
// Incoming messages
ws.onmessage = function(event) {
document.body.innerHTML += event.data + '<br/>';
};
// Outgoing messages
window.setInterval(function () { ws.send('Hello Mojo!') }, 1000);
</script>
</body>
</html>
The event L<Mojo::Transaction::WebSocket/"finish"> will be emitted right after
the WebSocket connection has been closed.
$c->tx->with_compression;
You can activate C<permessage-deflate> compression with
L<Mojo::Transaction::WebSocket/"with_compression">, this can result in much
better performance, but also increases memory usage by up to 300KB per
connection.
=head2 Testing WebSocket web services
While the message flow on WebSocket connections can be rather dynamic, it
more often than not is quite predictable, which allows this rather pleasant
L<Test::Mojo> API to be used.
use Test::More;
use Test::Mojo;
# Include application
use FindBin;
require "$FindBin::Bin/../echo.pl";
# Test echo web service
my $t = Test::Mojo->new;
$t->websocket_ok('/echo')
->send_ok('Hello Mojo!')
->message_ok
->message_is('echo: Hello Mojo!')
->finish_ok;
# Test JSON web service
$t->websocket_ok('/echo.json')
->send_ok({json => {test => [1, 2, 3]}})
->message_ok
->json_message_is('/test', [1, 2, 3])
->finish_ok;
done_testing();
=head2 EventSource web service
EventSource is a special form of long polling where you can use
L<Mojolicious::Controller/"write"> to directly send DOM events from servers to
clients. It is uni-directional, that means you will have to use Ajax requests
for sending data from clients to servers, the advantage however is low
infrastructure requirements, since it reuses the HTTP protocol for transport.
use Mojolicious::Lite;
# Template with browser-side code
get '/' => 'index';
# EventSource for log messages
get '/events' => sub {
my $c = shift;
# Increase inactivity timeout for connection a bit
$c->inactivity_timeout(300);
# Change content type
$c->res->headers->content_type('text/event-stream');
# Subscribe to "message" event and forward "log" events to browser
my $cb = $c->app->log->on(message => sub {
my ($log, $level, @lines) = @_;
$c->write("event:log\ndata: [$level] @lines\n\n");
});
# Unsubscribe from "message" event again once we are done
$c->on(finish => sub {
my $c = shift;
$c->app->log->unsubscribe(message => $cb);
});
};
app->start;
__DATA__
@@ index.html.ep
<!DOCTYPE html>
<html>
<head><title>LiveLog</title></head>
<body>
<script>
var events = new EventSource('<%= url_for 'events' %>');
// Subscribe to "log" event
events.addEventListener('log', function(event) {
document.body.innerHTML += event.data + '<br/>';
}, false);
</script>
</body>
</html>
The event L<Mojo::Log/"message"> will be emitted for every new log message and
the event L<Mojo::Transaction/"finish"> right after the transaction has been
finished.
=head2 Streaming multipart uploads
L<Mojolicious> contains a very sophisticated event system based on
L<Mojo::EventEmitter>, with ready-to-use events on almost all layers, and
which can be combined to solve some of hardest problems in web development.
use Mojolicious::Lite;
use Scalar::Util 'weaken';
# Intercept multipart uploads and log each chunk received
hook after_build_tx => sub {
my $tx = shift;
# Subscribe to "upgrade" event to indentify multipart uploads
weaken $tx;
$tx->req->content->on(upgrade => sub {
my ($single, $multi) = @_;
return unless $tx->req->url->path->contains('/upload');
# Subscribe to "part" event to find the right one
$multi->on(part => sub {
my ($multi, $single) = @_;
# Subscribe to "body" event of part to make sure we have all headers
$single->on(body => sub {
my $single = shift;
# Make sure we have the right part and replace "read" event
return unless $single->headers->content_disposition =~ /example/;
$single->unsubscribe('read')->on(read => sub {
my ($single, $bytes) = @_;
# Log size of every chunk we receive
app->log->debug(length($bytes) . ' bytes uploaded.');
});
});
});
});
};
# Upload form in DATA section
get '/' => 'index';
# Streaming multipart upload
post '/upload' => {text => 'Upload was successful.'};
app->start;
__DATA__
@@ index.html.ep
<!DOCTYPE html>
<html>
<head><title>Streaming multipart upload</title></head>
<body>
%= form_for upload => (enctype => 'multipart/form-data') => begin
%= file_field 'example'
%= submit_button 'Upload'
% end
</body>
</html>
=head2 Event loops
Internally the L<Mojo::IOLoop> event loop can use multiple reactor backends,
L<EV> for example will be automatically used if installed. Which in turn
allows other event loops like L<AnyEvent> to just work.
use Mojolicious::Lite;
use EV;
use AnyEvent;
# Wait 3 seconds before rendering a response
get '/' => sub {
my $c = shift;
my $w;
$w = AE::timer 3, 0, sub {
$c->render(text => 'Delayed by 3 seconds!');
undef $w;
};
};
app->start;
Who actually controls the event loop backend is not important.
use Mojo::UserAgent;
use EV;
use AnyEvent;
# Search MetaCPAN for "mojolicious"
my $cv = AE::cv;
my $ua = Mojo::UserAgent->new;
$ua->get('api.metacpan.org/v0/module/_search?q=mojolicious' => sub {
my ($ua, $tx) = @_;
$cv->send($tx->res->json('/hits/hits/0/_source/release'));
});
say $cv->recv;
You could for example just embed the built-in web server into an L<AnyEvent>
application.
use Mojolicious::Lite;
use Mojo::Server::Daemon;
use EV;
use AnyEvent;
# Normal action
get '/' => {text => 'Hello World!'};
# Connect application with web server and start accepting connections
my $daemon
= Mojo::Server::Daemon->new(app => app, listen => ['http://*:8080']);
$daemon->start;
# Let AnyEvent take control
AE::cv->recv;
=head1 USER AGENT
When we say L<Mojolicious> is a web framework we actually mean it, with
L<Mojo::UserAgent> there's a full featured HTTP and WebSocket user agent built
right in.
=head2 Web scraping
Scraping information from web sites has never been this much fun before. The
built-in HTML/XML parser L<Mojo::DOM> is accessible through
L<Mojo::Message/"dom"> and supports all CSS selectors that make sense for a
standalone parser, it can be a very powerful tool especially for testing web
application.
use Mojo::UserAgent;
# Fetch web site
my $ua = Mojo::UserAgent->new;
my $tx = $ua->get('mojolicio.us/perldoc');
# Extract title
say 'Title: ', $tx->res->dom->at('head > title')->text;
# Extract headings
$tx->res->dom('h1, h2, h3')->each(sub { say 'Heading: ', shift->all_text });
# Visit all nodes recursively to extract more than just text
for my $n ($tx->res->dom->all_contents->each) {
# Text or CDATA node
print $n->content if $n->node eq 'text' || $n->node eq 'cdata';
# Also include alternate text for images
print $n->{alt} if $n->node eq 'tag' && $n->type eq 'img';
}
For a full list of available CSS selectors see L<Mojo::DOM::CSS/"SELECTORS">.
=head2 JSON web services
Most web services these days are based on the JSON data-interchange format.
That's why L<Mojolicious> comes with the possibly fastest pure-Perl
implementation L<Mojo::JSON> built right in, it is accessible through
L<Mojo::Message/"json">.
use Mojo::UserAgent;
use Mojo::URL;
# Fresh user agent
my $ua = Mojo::UserAgent->new;
# Search MetaCPAN for "mojolicious" and list latest releases
my $url = Mojo::URL->new('http://api.metacpan.org/v0/release/_search');
$url->query({q => 'mojolicious', sort => 'date:desc'});
for my $hit (@{$ua->get($url)->res->json->{hits}{hits}}) {
say "$hit->{_source}{name} ($hit->{_source}{author})";
}
=head2 Basic authentication
You can just add username and password to the URL, an C<Authorization> header
will be automatically generated.
use Mojo::UserAgent;
my $ua = Mojo::UserAgent->new;
say $ua->get('https://sri:secret@example.com/hideout')->res->body;
=head2 Decorating followup requests
L<Mojo::UserAgent> can automatically follow redirects, the event
L<Mojo::UserAgent/"start"> allows you direct access to each transaction right
after they have been initialized and before a connection gets associated with
them.
use Mojo::UserAgent;
# User agent following up to 10 redirects
my $ua = Mojo::UserAgent->new(max_redirects => 10);
# Add a witty header to every request
$ua->on(start => sub {
my ($ua, $tx) = @_;
$tx->req->headers->header('X-Bender' => 'Bite my shiny metal ass!');
say 'Request: ', $tx->req->url->clone->to_abs;
});
# Request that will most likely get redirected
say 'Title: ', $ua->get('google.com')->res->dom->at('head > title')->text;
This even works for proxy C<CONNECT> requests.
=head2 Content generators
Content generators can be registered with
L<Mojo::UserAgent::Transactor/"add_generator"> to generate the same type of
content repeatedly for multiple requests.
use Mojo::UserAgent;
use Mojo::Asset::File;
# Add "stream" generator
my $ua = Mojo::UserAgent->new;
$ua->transactor->add_generator(stream => sub {
my ($transactor, $tx, $path) = @_;
$tx->req->content->asset(Mojo::Asset::File->new(path => $path));
});
# Send multiple files streaming via PUT and POST
$ua->put('http://example.com/upload' => stream => '/home/sri/mojo.png');
$ua->post('http://example.com/upload' => stream => '/home/sri/minion.png');
The C<json> and C<form> content generators are always available.
use Mojo::UserAgent;
# Send "application/json" content via PATCH
my $ua = Mojo::UserAgent->new;
my $tx = $ua->patch('http://api.example.com' => json => {foo => 'bar'});
# Send query parameters via GET
my $tx2 = $ua->get('http://search.example.com' => form => {q => 'test'});
# Send "application/x-www-form-urlencoded" content via POST
my $tx3 = $ua->post('http://search.example.com' => form => {q => 'test'});
# Send "multipart/form-data" content via PUT
my $tx4 = $ua->put('http://upload.example.com' =>
form => {test => {content => 'Hello World!'}});
For more information about available content generators see also
L<Mojo::UserAgent::Transactor/"tx">.
=head2 Large file downloads
When downloading large files with L<Mojo::UserAgent> you don't have to worry
about memory usage at all, because it will automatically stream everything
above 250KB into a temporary file, which can then be moved into a permanent
file with L<Mojo::Asset::File/"move_to">.
use Mojo::UserAgent;
# Lets fetch the latest Mojolicious tarball
my $ua = Mojo::UserAgent->new(max_redirects => 5);
my $tx = $ua->get('https://www.github.com/kraih/mojo/tarball/master');
$tx->res->content->asset->move_to('mojo.tar.gz');
To protect you from excessively large files there is also a limit of 10MB by
default, which you can tweak with the attribute
L<Mojo::Message/"max_message_size"> or C<MOJO_MAX_MESSAGE_SIZE> environment
variable.
# Increase limit to 1GB
$ENV{MOJO_MAX_MESSAGE_SIZE} = 1073741824;
=head2 Large file upload
Uploading a large file is even easier.
use Mojo::UserAgent;
# Upload file via POST and "multipart/form-data"
my $ua = Mojo::UserAgent->new;
$ua->post('example.com/upload' =>
form => {image => {file => '/home/sri/hello.png'}});
And once again you don't have to worry about memory usage, all data will be
streamed directly from the file.
=head2 Streaming response
Receiving a streaming response can be really tricky in most HTTP clients, but
L<Mojo::UserAgent> makes it actually easy.
use Mojo::UserAgent;
# Build a normal transaction
my $ua = Mojo::UserAgent->new;
my $tx = $ua->build_tx(GET => 'http://example.com');
# Accept response of indefinite size
$tx->res->max_message_size(0);
# Replace "read" events to disable default content parser
$tx->res->content->unsubscribe('read')->on(read => sub {
my ($content, $bytes) = @_;
say "Streaming: $bytes";
});
# Process transaction
$tx = $ua->start($tx);
The event L<Mojo::Content/"read"> will be emitted for every chunk of data that
is received, even C<chunked> encoding and gzip compression will be handled
transparently if necessary.
=head2 Streaming request
Sending a streaming request is almost just as easy.
use Mojo::UserAgent;
# Build a normal transaction
my $ua = Mojo::UserAgent->new;
my $tx = $ua->build_tx(GET => 'http://example.com');
# Prepare body
my $body = 'Hello world!';
$tx->req->headers->content_length(length $body);
# Start writing directly with a drain callback
my $drain;
$drain = sub {
my $content = shift;
my $chunk = substr $body, 0, 1, '';
$drain = undef unless length $body;
$content->write($chunk, $drain);
};
$tx->req->content->$drain;
# Process transaction
$tx = $ua->start($tx);
The drain callback passed to L<Mojo::Content/"write"> will be invoked whenever
the entire previous chunk has actually been written.
=head2 Non-blocking
L<Mojo::UserAgent> has been designed from the ground up to be non-blocking,
the whole blocking API is just a simple convenience wrapper. Especially for
high latency tasks like web crawling this can be extremely useful, because you
can keep many concurrent connections active at the same time.
use Mojo::UserAgent;
use Mojo::IOLoop;
# Concurrent non-blocking requests
my $ua = Mojo::UserAgent->new;
$ua->get('http://metacpan.org/search?q=mojo' => sub {
my ($ua, $mojo) = @_;
...
});
$ua->get('http://metacpan.org/search?q=minion' => sub {
my ($ua, $minion) = @_;
...
});
# Start event loop if necessary
Mojo::IOLoop->start unless Mojo::IOLoop->is_running;
You can take full control of the L<Mojo::IOLoop> event loop.
=head2 Concurrent blocking requests
You can emulate blocking behavior by using L<Mojo::IOLoop/"delay"> to
synchronize multiple non-blocking requests.
use Mojo::UserAgent;
use Mojo::IOLoop;
# Synchronize non-blocking requests
my $ua = Mojo::UserAgent->new;
my $delay = Mojo::IOLoop->delay(sub {
my ($delay, $mojo, $minion) = @_;
...
});
$ua->get('http://metacpan.org/search?q=mojo' => $delay->begin);
$ua->get('http://metacpan.org/search?q=minion' => $delay->begin);
$delay->wait;
The call to L<Mojo::IOLoop::Delay/"wait"> makes this code portable, it can now
work inside an already running event loop or start one on demand.
=head2 WebSockets
WebSockets are not just for the server-side, you can use
L<Mojo::UserAgent/"websocket"> to open new connections, which are always
non-blocking. The handshake is a normal HTTP request with a few additional
headers, it can even contain cookies, followed by a C<101> response from the
server notifying our user agent that the connection has been established and
it can start using the bi-directional WebSocket protocol.
use Mojo::UserAgent;
use Mojo::IOLoop;
# Open WebSocket to echo service
my $ua = Mojo::UserAgent->new;
$ua->websocket('ws://echo.websocket.org' => sub {
my ($ua, $tx) = @_;
# Check if WebSocket handshake was successful
say 'WebSocket handshake failed!' and return unless $tx->is_websocket;
# Wait for WebSocket to be closed
$tx->on(finish => sub {
my ($tx, $code, $reason) = @_;
say "WebSocket closed with status $code.";
});
# Close WebSocket after receiving one message
$tx->on(message => sub {
my ($tx, $msg) = @_;
say "WebSocket message: $msg";
$tx->finish;
});
# Send a message to the server
$tx->send('Hi!');
});
# Start event loop if necessary
Mojo::IOLoop->start unless Mojo::IOLoop->is_running;
=head2 Command line
Don't you hate checking huge HTML files from the command line? Thanks to the
command L<Mojolicious::Command::get> that is about to change. You can just
pick the parts that actually matter with the CSS selectors from L<Mojo::DOM>
and JSON Pointers from L<Mojo::JSON::Pointer>.
$ mojo get http://mojolicio.us 'head > title'
How about a list of all id attributes?
$ mojo get http://mojolicio.us '*' attr id
Or the text content of all heading tags?
$ mojo get http://mojolicio.us 'h1, h2, h3' text
Maybe just the text of the third heading?
$ mojo get http://mojolicio.us 'h1, h2, h3' 3 text
You can also extract all text from nested child elements.
$ mojo get http://mojolicio.us '#mojobar' all
The request can be customized as well.
$ mojo get -M POST -c 'Hello!' http://mojolicio.us
$ mojo get -H 'X-Bender: Bite my shiny metal ass!' http://google.com
You can follow redirects and view the headers for all messages.
$ mojo get -r -v http://google.com 'head > title'
Extract just the information you really need from JSON data structures.
$ mojo get https://api.metacpan.org/v0/author/SRI /name
This can be an invaluable tool for testing your applications.
$ ./myapp.pl get /welcome 'head > title'
=head2 One-liners
For quick hacks and especially testing, L<ojo> one-liners are also a great
choice.
$ perl -Mojo -E 'say g("mojolicio.us")->dom->html->head->title->text'
=head1 APPLICATIONS
Fun L<Mojolicious> application hacks for all occasions.
=head2 Basic authentication
Basic authentication data will be automatically extracted from the
C<Authorization> header.
use Mojolicious::Lite;
get '/' => sub {
my $c = shift;
# Check for username "Bender" and password "rocks"
return $c->render(text => 'Hello Bender!')
if $c->req->url->to_abs->userinfo eq 'Bender:rocks';
# Require authentication
$c->res->headers->www_authenticate('Basic');
$c->render(text => 'Authentication required!', status => 401);
};
app->start;
This can be combined with TLS for a secure authentication mechanism.
$ ./myapp.pl daemon -l 'https://*:3000?cert=./server.crt&key=./server.key'
=head2 Adding a configuration file
Adding a configuration file to your application is as easy as adding a file to
its home directory and loading the plugin L<Mojolicious::Plugin::Config>. The
default name is based on the value of L<Mojolicious/"moniker"> (C<myapp>),
appended with a C<.conf> extension (C<myapp.conf>).
$ mkdir myapp
$ cd myapp
$ touch myapp.pl
$ chmod 744 myapp.pl
$ echo '{name => "my Mojolicious application"};' > myapp.conf
Configuration files themselves are just Perl scripts that return a hash
reference, all settings are available through the method L<Mojo/"config"> and
the helper L<Mojolicious::Plugin::DefaultHelpers/"config">
use Mojolicious::Lite;
plugin 'Config';
my $name = app->config('name');
app->log->debug("Welcome to $name.");
get '/' => 'with_config';
app->start;
__DATA__
@@ with_config.html.ep
<!DOCTYPE html>
<html>
<head><title><%= config 'name' %></title></head>
<body>Welcome to <%= config 'name' %></body>
</html>
Alternatively you can also use configuration files in the JSON format with
L<Mojolicious::Plugin::JSONConfig>.
=head2 Adding a plugin to your application
To organize your code better and to prevent helpers from cluttering your
application, you can use application specific plugins.
$ mkdir -p lib/MyApp/Plugin
$ touch lib/MyApp/Plugin/MyHelpers.pm
They work just like normal plugins and are also subclasses of
L<Mojolicious::Plugin>. Nested helpers with a prefix based on the plugin name
are an easy way to avoid conflicts.
package MyApp::Plugin::MyHelpers;
use Mojo::Base 'Mojolicious::Plugin';
sub register {
my ($self, $app) = @_;
$app->helper('my_helpers.render_with_header' => sub {
my ($c, @args) = @_;
$c->res->headers->header('X-Mojo' => 'I <3 Mojolicious!');
$c->render(@args);
});
}
1;
You can have as many application specific plugins as you like, the only
difference to normal plugins is that you load them using their full class
name.
use Mojolicious::Lite;
use lib 'lib';
plugin 'MyApp::Plugin::MyHelpers';
get '/' => sub {
my $c = shift;
$c->my_helpers->render_with_header(text => 'I ♥ Mojolicious!');
};
app->start;
Of course these plugins can contain more than just helpers, take a look at
L<Mojolicious::Plugins/"PLUGINS"> for a few ideas.
=head2 Adding commands to Mojolicious
By now you've probably used many of the built-in commands described in
L<Mojolicious::Commands>, but did you know that you can just add new ones and
that they will be picked up automatically by the command line interface?
package Mojolicious::Command::spy;
use Mojo::Base 'Mojolicious::Command';
has description => 'Spy on application.';
has usage => "Usage: APPLICATION spy [TARGET]\n";
sub run {
my ($self, @args) = @_;
# Leak secret passphrases
say for @{$self->app->secrets} if $args[0] eq 'secrets';
# Leak mode
say $self->app->mode if $args[0] eq 'mode';
}
1;
Command line arguments are passed right through and there are many useful
attributes and methods in L<Mojolicious::Command> that you can use or
overload.
$ mojo spy secrets
HelloWorld
$ ./myapp.pl spy secrets
secr3t
And to make your commands application specific, just add a custom namespace to
L<Mojolicious::Commands/"namespaces">.
# Application
package MyApp;
use Mojo::Base 'Mojolicious';
sub startup {
my $self = shift;
# Add another namespace to load commands from
push @{$self->commands->namespaces}, 'MyApp::Command';
}
1;
Some options like C<-m> for the operating mode of your application are shared
by all commands automatically.
$ ./myapp.pl spy -m production mode
production
For a full list of shared options see L<Mojolicious::Commands/"SYNOPSIS">.
=head2 Running code against your application
Ever thought about running a quick one-liner against your L<Mojolicious>
application to test something? Thanks to the command
L<Mojolicious::Command::eval> you can do just that, the application object
itself can be accessed via C<app>.
$ mojo generate lite_app myapp.pl
$ ./myapp.pl eval 'say for @{app->static->paths}'
The C<verbose> options will automatically print the return value or returned
data structure to C<STDOUT>.
$ ./myapp.pl eval -v 'app->static->paths->[0]'
$ ./myapp.pl eval -V 'app->static->paths'
=head2 Making your application installable
Ever thought about releasing your L<Mojolicious> application to CPAN? It's
actually much easier than you might think.
$ mojo generate app MyApp
$ cd my_app
$ mv public lib/MyApp/
$ mv templates lib/MyApp/
The trick is to move the C<public> and C<templates> directories so they can
get automatically installed with the modules.
# Application
package MyApp;
use Mojo::Base 'Mojolicious';
use File::Basename 'dirname';
use File::Spec::Functions 'catdir';
# Every CPAN module needs a version
our $VERSION = '1.0';
sub startup {
my $self = shift;
# Switch to installable home directory
$self->home->parse(catdir(dirname(__FILE__), 'MyApp'));
# Switch to installable "public" directory
$self->static->paths->[0] = $self->home->rel_dir('public');
# Switch to installable "templates" directory
$self->renderer->paths->[0] = $self->home->rel_dir('templates');
$self->plugin('PODRenderer');
my $r = $self->routes;
$r->get('/welcome')->to('example#welcome');
}
1;
That's really everything, now you can package your application like any other
CPAN module.
$ ./script/my_app generate makefile
$ perl Makefile.PL
$ make test
$ make manifest
$ make dist
And if you have a PAUSE account (which can be requested at
L<http://pause.perl.org>) even upload it.
$ mojo cpanify -u USER -p PASS MyApp-0.01.tar.gz
=head2 Hello World
If every byte matters this is the smallest C<Hello World> application you can
write with L<Mojolicious::Lite>.
use Mojolicious::Lite;
any {text => 'Hello World!'};
app->start;
It works because all routes without a pattern default to C</> and automatic
rendering kicks in even if no actual code gets executed by the router. The
renderer just picks up the C<text> value from the stash and generates a
response.
=head2 Hello World one-liners
The C<Hello World> example above can get even a little bit shorter in an
L<ojo> one-liner.
$ perl -Mojo -E 'a({text => "Hello World!"})->start' daemon
And you can use all the commands from L<Mojolicious::Commands>.
$ perl -Mojo -E 'a({text => "Hello World!"})->start' get -v /
=head1 MORE
You can continue with L<Mojolicious::Guides> now or take a look at the
L<Mojolicious wiki|http://github.com/kraih/mojo/wiki>, which contains a lot
more documentation and examples by many different authors.
=head1 SUPPORT
If you have any questions the documentation might not yet answer, don't
hesitate to ask on the
L<mailing-list|http://groups.google.com/group/mojolicious> or the official IRC
channel C<#mojo> on C<irc.perl.org>.
=cut
|