/usr/share/perl5/Dancer2/Cookbook.pod is in libdancer2-perl 0.152000+dfsg-1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
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 | package Dancer2::Cookbook;
# ABSTRACT: Example-driven quick-start to the Dancer2 web framework
$Dancer2::Cookbook::VERSION = '0.152000';
__END__
=pod
=encoding UTF-8
=head1 NAME
Dancer2::Cookbook - Example-driven quick-start to the Dancer2 web framework
=head1 VERSION
version 0.152000
=head1 DESCRIPTION
A quick-start guide with examples to get you up and running with the Dancer2
web framework.
=head1 BEGINNER'S DANCE
=head2 A simple Dancer2 web app
Dancer2 has been designed to be easy to work with - it's trivial to write a
simple web app, but still has the power to work with larger projects. To
start with, let's make an incredibly simple "Hello World" example:
#!/usr/bin/perl
use Dancer2;
get '/hello/:name' => sub {
return "Why, hello there " . params->{name};
};
dance;
Yes - the above is a fully-functioning web app; running that script will
launch a webserver listening on the default port (3000). Now you can make a
request
$ curl http://localhost:3000/hello/Bob
Why, hello there Bob
and it will say hello. The C<:name> part is a named parameter within the
route specification, whose value is made available through C<params>.
Note that you don't need to use the C<strict> and C<warnings> pragmas; they
are already loaded by Dancer2.
=head2 Starting a Dancer2 project
The above simple example is fine for trivial projects, but for anything more
complex, you'll want a more maintainable solution - enter the C<dancer2>
helper script, which will build the framework of your application with a
single command:
$ dancer2 -a mywebapp
+ mywebapp
+ mywebapp/bin
+ mywebapp/bin/app.pl
+ mywebapp/config.yml
+ mywebapp/environments
+ mywebapp/environments/development.yml
+ mywebapp/environments/production.yml
+ mywebapp/views
+ mywebapp/views/index.tt
+ mywebapp/views/layouts
+ mywebapp/views/layouts/main.tt
+ mywebapp/MANIFEST.SKIP
+ mywebapp/lib
+ mywebapp/lib/
+ mywebapp/lib/mywebapp.pm
+ mywebapp/public
+ mywebapp/public/css
+ mywebapp/public/css/style.css
+ mywebapp/public/css/error.css
+ mywebapp/public/images
+ mywebapp/public/500.html
+ mywebapp/public/404.html
+ mywebapp/public/dispatch.fcgi
+ mywebapp/public/dispatch.cgi
+ mywebapp/public/javascripts
+ mywebapp/public/javascripts/jquery.js
+ mywebapp/t
+ mywebapp/t/002_index_route.t
+ mywebapp/t/001_base.t
+ mywebapp/Makefile.PL
As you can see, it creates a directory named after the name of the app,
along with a configuration file, a views directory (where your templates and
layouts will live), an environments directory (where environment-specific
settings live), a module containing the actual guts of your application and
a script to start it - or to run your web app via Plack/PSGI.
=head1 DANCE ROUTINES: ROUTES
=head2 Declaring routes
To control what happens when a web request is received by your webapp,
you'll need to declare C<routes>. A route declaration indicates which HTTP
method(s) it is valid for, the path it matches (e.g. C</foo/bar>), and a
coderef to execute, which returns the response.
get '/hello/:name' => sub {
return "Hi there " . params->{name};
};
The above route specifies that, for GET requests to C</hello/...>, the code
block provided should be executed.
=head2 Handling multiple HTTP request methods
Routes can use C<any> to match all, or a specified list of HTTP methods.
The following will match any HTTP request to the path C</myaction>:
any '/myaction' => sub {
# code
}
The following will match GET or POST requests to C</myaction>:
any ['get', 'post'] => '/myaction' => sub {
# code
};
For convenience, any route which matches GET requests will also match HEAD
requests.
=head2 Retrieving request parameters
The L<params|Dancer2/params> keyword returns a hashref of request
parameters; these will be parameters supplied on the query string within
the path itself (with named placeholders) and, for HTTTP POST requests, the
content of the POST body.
=head2 Named parameters in route path declarations
As seen above, you can use C<:somename> in a route's path to capture part of the
path; this will become available by calling L<params|Dancer2/params>.
So, for a web app where you want to display information on a company, you might
use something like:
get '/company/view/:companyid' => sub {
my $company_id = params->{companyid};
# Look up the company and return appropriate page
};
=head2 Wildcard path matching and splat
You can also declare wildcards in a path and retrieve the values they matched
with the L<splat|Dancer2/splat> keyword:
get '/*/*' => sub {
my ($action, $id) = splat;
if (my $action eq 'view') {
return display_item($id);
} elsif ($action eq 'delete') {
return delete_item($id);
} else {
status 'not_found';
return "What?";
}
};
=head2 Before filters - processed before a request
A L<before|Dancer2/before> filter declares code which should be handled before
a request is passed to the appropriate route.
hook before => sub {
forward '/foo/oversee', { note => 'Hi there' };
};
get '/foo/*' => sub {
my ($match) = splat; # 'oversee';
params->{note}; # 'Hi there'
};
The above declares a before filter which uses C<forward> to do an internal
redirect to C</foo/oversee> with an additional parameter C<note>.
See also the L<hook|Dancer2/hook> keyword.
=head2 Default route
In case you want to avoid a I<404 error>, or handle multiple routes in the
same way and you don't feel like configuring all of them, you can set up a
default route handler.
The default route handler will handle any request that doesn't get served by
any other route.
All you need to do is set up the following route as the B<last> route:
any qr{.*} => sub {
status 'not_found';
template 'special_404', { path => request->path };
};
Then you can set up the template like so:
You tried to reach [% path %], but it is unavailable at the moment.
Please try again or contact us at <contact@example.com>.
=head2 Using the C<auto_page> feature for automatic route creation
For simple "static" pages you can simply enable the C<auto_page> config
setting; this means you don't need to declare a route handler for those
pages; if a request is for C</foo/bar>, Dancer2 will check for a matching
view (e.g. C</foo/bar.tt> and render it with the default layout etc. if
found. For full details, see the documentation for the L<auto_page
setting|Dancer2::Config/"auto_page">.
=head2 Simplifying Ajax queries with the Ajax plugin
As an Ajax query is just an HTTP query, it's similar to a GET or POST route.
You may ask yourself why you may want to use the C<ajax> keyword (from the
L<Dancer2::Plugin::Ajax> plugin) instead of a simple C<get>.
Let's say you have a path like C</user/:user> in your application. You may
want to be able to serve this page with a layout and HTML content. But you
may also want to be able to call this same url from a javascript query using
Ajax.
So, instead of having the following code:
get '/user/:user' => sub {
if (request->is_ajax) {
# create xml, set headers to text/xml, blablabla
header('Content-Type' => 'text/xml');
header('Cache-Control' => 'no-store, no-cache, must-revalidate');
to_xml({...})
}else{
template users, {....}
}
};
you can have
get '/user/:user' => sub {
template users, {...}
}
and
ajax '/user/:user' => sub {
to_xml({...}, RootName => undef);
}
Because it's an Ajax query, you know you need to return XML content, so
the content type of the response is set for you.
=head2 Using the prefix feature to split your application
For better maintainability, you may want to separate some of your application
components into different packages. Let's say we have a simple web app with an
admin section and want to maintain this in a different package:
package myapp;
use Dancer2;
use myapp::admin;
prefix undef;
get '/' => sub {...};
1;
package myapp::admin;
use Dancer2 appname => 'myapp';
prefix '/admin';
get '/' => sub {...};
1;
The following routes will be generated for us:
- get /
- get /admin/
- head /
- head /admin/
By default, a separate application is created for every package that uses
Dancer2. The C<appname> tag is used to collect routes and hooks into a
single Dancer2 application. In the above example, C<appname =E<gt> 'myapp'>
adds the routes from C<myapp::admin> to the routes of the app C<myapp>.
When using multiple applications please ensure that your path definitions do
not overlap. For example, if using a default route as described above, once
a request is matched to the default route then no further routes (or
applications) would be reached.
=head1 MUSCLE MEMORY: STORING DATA
=head2 Handling sessions
It's common to want to use sessions to give your web applications state; for
instance, allowing a user to log in, creating a session, and checking that
session on subsequent requests.
To make use of sessions, you must first enable the session engine - pick the
session engine you want to use, then declare it in your config file like
this:
session: Simple
The L<Dancer2::Session::Simple> backend implements very simple in-memory
session storage. This will be fast and useful for testing, but such sessions
will not persist between restarts of your app.
You can also use the L<Dancer2::Session::YAML> backend included with
Dancer2, which stores session data on disc in YAML files (since YAML is a
nice human-readable format, it makes inspecting the contents of sessions a
breeze):
session: YAML
Or, to enable session support from within your code,
set session => 'YAML';
However, controlling settings is best done from your config file.
'YAML' in the example is the session backend to use; this is shorthand for
L<Dancer2::Session::YAML>. There are other session backends - for instance
L<Dancer2::Session::Memcached> - but the YAML backend is simple and easy to
use.
You can then use the L<session|Dancer2/session> keyword to manipulate the
session:
=head3 Storing data in the session
Storing data in the session is as easy as:
session varname => 'value';
=head3 Retrieving data from the session
Retrieving data from the session is as easy as:
session('varname')
Or, alternatively,
session->read("varname")
=head3 Controlling where sessions are stored
For disc-based session backends like L<Dancer2::Session::YAML>,
L<Dancer2::Session::Storable> etc., session files are written to the session
dir specified by the C<session_dir> setting, which defaults to C<./sessions>
if not specifically set.
If you need to control where session files are created, you can do so
quickly and easily within your config file, for example:
session: YAML
engines:
session:
YAML:
session_dir: /tmp/dancer-sessions
If the directory you specify does not exist, Dancer2 will attempt to create
it for you.
=head3 Destroying a session
When you're done with your session, you can destroy it:
app->destroy_session
=head2 Sessions and logging in
B<Note!> The following example will in this form prevent the application
from returning static content (files inside the C<public/> directory, like CSS,
javascript files etc.) when the user is not logged in, because the before hook
is executed on the static files as well. A simple way to prevent this is using
L<Plack::Middleware::Static> for serving static files. An example can be found
L<here|Dancer2::Cookbook/"Serving_static_files_using_Plack::Middleware::Static">.
A common requirement is to check the user is logged in, and, if not, require
them to log in before continuing.
This can easily be handled with a before filter to check their session:
use Dancer2;
set session => "Simple";
hook before => sub {
if (!session('user') && request->dispatch_path !~ m{^/login}) {
forward '/login', { requested_path => request->dispatch_path };
}
};
get '/' => sub { return "Home Page"; };
get '/secret' => sub { return "Top Secret Stuff here"; };
get '/login' => sub {
# Display a login page; the original URL they requested is available as
# param('requested_path'), so could be put in a hidden field in the form
template 'login', { path => param('requested_path') };
};
post '/login' => sub {
# Validate the username and password they supplied
if (param('user') eq 'bob' && param('pass') eq 'letmein') {
session user => param('user');
redirect param('path') || '/';
} else {
redirect '/login?failed=1';
}
};
dance();
Here is what the corresponding C<login.tt> file should look like. You should
place it in a directory called C<views/>:
<html>
<head>
<title>Session and logging in</title>
</head>
<body>
<form action='/login' method='POST'>
User Name : <input type='text' name='user'/>
Password: <input type='password' name='pass' />
<!-- Put the original path requested into a hidden
field so it's sent back in the POST and can be
used to redirect to the right page after login -->
<input type='hidden' name='path' value='[% path %]'/>
<input type='submit' value='Login' />
</form>
</body>
</html>
Of course, you'll probably want to validate your users against a database
table, or maybe via IMAP/LDAP/SSH/POP3/local system accounts via PAM etc.
L<Authen::Simple> is probably a good starting point here!
A simple working example of handling authentication against a database table
yourself (using L<Dancer2::Plugin::Database> which provides the C<database>
keyword, and L<Crypt::SaltedHash> to handle salted hashed passwords (well,
you wouldn't store your users passwords in the clear, would you?)) follows:
post '/login' => sub {
my $user = database->quick_select('users',
{ username => params->{user} }
);
if (!$user) {
warning "Failed login for unrecognised user " . params->{user};
redirect '/login?failed=1';
} else {
if (Crypt::SaltedHash->validate($user->{password}, params->{pass}))
{
debug "Password correct";
# Logged in successfully
session user => $user;
redirect params->{path} || '/';
} else {
debug("Login failed - password incorrect for " . params->{user});
redirect '/login?failed=1';
}
}
};
=head3 Retrieve complete hash stored in session
Get complete hash stored in session:
my $hash = session;
=head1 APPEARANCE: TEMPLATES AND LAYOUTS
Returning plain content is all well and good for examples or trivial apps,
but soon you'll want to use templates to maintain separation between your
code and your content. Dancer2 makes this easy.
Your route handlers can use the L<template|Dancer2::Manual/template> keyword
to render templates.
=head2 Views
It's possible to render the action's content with a template, this is called
a view. The C<appdir/views> directory is the place where views are located.
You can change this location by changing the setting 'views'.
By default, the internal template engine L<Dancer2::Template::Simple> is
used, but you may want to upgrade to L<Template
Toolkit|http://www.template-toolkit.org/>. If you do so, you have to enable
this engine in your settings as explained in
L<Dancer2::Template::TemplateToolkit> and you'll also have to import the
L<Template> module in your application code.
Views use a C<.tt> extension by convention. This can be overridden by
setting the C<extension> attribute in the template engine configuration.
See the L<Using Templates|Dancer2::Manual/"Using Templates"> section in the
manual for details.
In order to render a view, just call the
L<template|Dancer2::Manual/template> keyword at the end of the action by
giving the view name and the HASHREF of tokens to interpolate in the view
(note that for convenience, the request, session, params and vars are
automatically accessible in the view, named C<request>, C<session>,
C<params> and C<vars>) - for example:
hook before => sub { var time => scalar(localtime) };
get '/hello/:name' => sub {
my $name = params->{name};
template 'hello.tt', { name => $name };
};
The template C<hello.tt> could contain, for example:
<p>Hi there, [% name %]!</p>
<p>You're using [% request.user_agent %]</p>
[% IF session.username %]
<p>You're logged in as [% session.username %]</p>
[% END %]
It's currently [% vars.time %]
For a full list of the tokens automatically added to your template (like
C<session>, C<request> and C<vars>, refer to
L<Dancer2::Core::Role::Template>).
=head2 Layouts
A layout is a special view, located in the 'layouts' directory (inside the
views directory) which must have a token named C<content>. That token marks
the place where to render the action view. This lets you define a global
layout for your actions, and have each individual view contain only
specific content. This is a good thing to avoid lots of needless
duplication of HTML :)
Here is an example of a layout: C<views/layouts/main.tt> :
<html>
<head>...</head>
<body>
<div id="header">
...
</div>
<div id="content">
[% content %]
</div>
</body>
</html>
You can tell your app which layout to use with C<layout: name> in the config
file, or within your code:
set layout => 'main';
You can control which layout to use (or whether to use a layout at all) for
a specific request without altering the layout setting by passing an options
hashref as the third param to the template keyword:
template 'index.tt', {}, { layout => undef };
If your application is not mounted under root (C</>), you can use a
C<before_template> hook instead of hardcoding the path into your application for your
CSS, images and JavaScript:
hook before_template_render => sub {
my $tokens = shift;
$tokens->{uri_base} = request->base->path;
};
Then in your layout, modify your CSS inclusion as follows:
<link rel="stylesheet" href="[% uri_base %]/css/style.css" />
From now on you can mount your application wherever you want, without any
further modification of the CSS inclusion.
=head2 Templates and unicode
If you use L<Plack> and have a unicode problem with your Dancer2
application, don't forget to check if you have set your template engine to
use unicode, and set the default charset to UTF-8. So, if you are using
template toolkit, your config file will look like this:
charset: UTF-8
engines:
template:
template_toolkit:
ENCODING: utf8
=head2 Template Toolkit's WRAPPER directive in Dancer2
Dancer2 already provides a WRAPPER-like ability, which we call a "layout".
The reason we don't use Template Toolkit's WRAPPER (which also makes us incompatible with
it) is because not all template systems support it. Actually, most don't.
However, you might want to use it, and be able to define META variables and
regular L<Template::Toolkit> variables.
These few steps will get you there:
=over 4
=item * Disable the layout in Dancer2
You can do this by simply commenting (or removing) the C<layout>
configuration in the config file.
=item * Use the Template Toolkit template engine
Change the configuration of the template to Template Toolkit:
# in config.yml
template: "template_toolkit"
=item * Tell the Template Toolkit engine which wrapper to use
# in config.yml
# ...
engines:
template:
template_toolkit:
WRAPPER: layouts/main.tt
=back
Done! Everything will work fine out of the box, including variables and META
variables.
=head1 SETTING THE STAGE: CONFIGURATION AND LOGGING
=head2 Configuration and environments
Configuring a Dancer2 application can be done in many ways. The easiest one
(and maybe the dirtiest) is to put all your settings statements at the top
of your script, before calling the C<dance()> method.
Other ways are possible: for example, you can define all your settings in the file
C<appdir/config.yml>. For this, you must have installed the YAML module, and
of course, write the config file in YAML.
That's better than the first option, but it's still not perfect as you can't
switch easily from an environment to another without rewriting the config
file.
A better solution is to have one C<config.yml> file with default global
settings, like the following:
# appdir/config.yml
logger: 'file'
layout: 'main'
And then write as many environment files as you like in
C<appdir/environments>. That way, the appropriate environment config file
will be loaded according to the running environment (if none is specified,
it will be 'development').
Note that you can change the running environment using the C<--environment>
command line switch.
Typically, you'll want to set the following values in a development config
file:
# appdir/environments/development.yml
log: 'debug'
startup_info: 1
show_errors: 1
And in a production one:
# appdir/environments/production.yml
log: 'warning'
startup_info: 0
show_errors: 0
=head2 Accessing configuration information
=head3 From inside your application
A Dancer2 application can use the C<config> keyword to easily access the
settings within its config file, for instance:
get '/appname' => sub {
return "This is " . config->{appname};
};
This makes keeping your application's settings all in one place simple and
easy - you shouldn't need to worry about implementing all that yourself :)
=head3 From a separate script
You may want to access your webapp's configuration from outside your
webapp. You could, of course, use the YAML module of your choice and load
your webapps's C<config.yml>, but chances are that this is not convenient.
Use Dancer2 instead. You can simply use
the values from C<config.yml> and some additional default values:
# bin/show_app_config.pl
use Dancer2;
print "template:".config->{template}."\n"; # simple
print "log:".config->{log}."\n"; # undef
Note that C<< config->{log} >> should result in an C<undef> error on a default
scaffold since the environment isn't loaded and
log is defined in the environment and not in C<config.yml>. Hence C<undef>.
If you want to load an environment you need to tell Dancer2 where to look
for it. One way to do so is to tell Dancer2 where the webapp lives. From
there Dancer2 deduces where the config.yml file is (typically
C<$webapp/config.yml>).
# bin/show_app_config_and_env.pl
use FindBin;
use Cwd qw/realpath/;
use Dancer2;
# tell the Dancer2 where the app lives
my $appdir = realpath( "$FindBin::Bin/..");
Dancer2::Config::setting('appdir', $appdir);
Dancer2::Config::load();
# getter
print "environment:".config->{environment}."\n"; # development
print "log:".config->{log}."\n"; # value from development environment
By default Dancer2 loads the development environment (typically
C<$webapp/environment/development.yml>). In contrast to the example above,
now you do have a value from the development environment
(C<environment/development.yml>). Also note that in the above example
L<Cwd> and L<FindBin> are used. They are likely to be already loaded by
Dancer2 anyways, so it's not a big overhead. You could just as well hand
over a simple path for the app if you like that better, e.g.:
Dancer2::Config::setting('appdir','/path/to/app/dir');
If you want to load an environment other than the default, try this:
# bin/show_app_config_and_env.pl
use Dancer2;
# tell the Dancer2 where the app lives
Dancer2::Config::setting('appdir', '/path/to/app/dir');
# which environment to load
config->{environment} = 'production';
Dancer2::Config::load();
# getter
print "log:".config->{log}."\n"; # has value from production environment
By the way, you not only get values, you can also set values straightforwardly
like we do above with C<< config->{environment}='production' >>. Of course,
this value does not get written in any file; it only lives in memory and thus
your webapp doesn't have access to it, but you can use it inside your
script.
=head2 Logging
=head3 Configuring logging
It's possible to log messages generated by the application and by Dancer2
itself.
To start logging, select the logging engine you wish to use with the
C<logger> setting; Dancer2 includes built-in log engines named C<file> and
C<console>, which log to a logfile and to the console respectively.
To enable logging to a file, add the following to your config file:
logger: 'file'
Then you can choose which kind of messages you want to actually log:
log: 'core' # will log debug, warnings, errors,
# and messages from Dancer2 itself
log: 'debug' # will log debug, info, warning and errors
log: 'info' # will log info, warning and errors
log: 'warning' # will log warning and errors
log: 'error' # will log only errors
If you're using the C<file> logging engine, a directory C<appdir/logs> will
be created and will host one logfile per environment. The log message
contains the time it was written, the PID of the current process, the
message and the caller information (file and line).
=head3 Logging your own messages
Just call L<debug|Dancer2/debug>, L<info|Dancer2/info>,
L<warning|Dancer2/warning> or L<error|Dancer2/error> with your message:
debug "This is a debug message from my app.";
=head1 RESTING
=head2 Writing a REST application
With Dancer2, it's easy to write REST applications. Dancer2 provides helpers
to serialize and deserialize for the following data formats:
=over 4
=item JSON
=item YAML
=item XML
=item Data::Dumper
=back
To activate this feature, you only have to set the C<serializer> setting to
the format you require, for instance in your config file:
serializer: JSON
Or directly in your code:
set serializer => 'JSON';
From now, all hashrefs or arrayrefs returned by a route will be serialized
to the format you chose, and all data received from B<POST> or B<PUT>
requests will be automatically deserialized.
get '/hello/:name' => sub {
# this structure will be returned to the client as
# {"name":"$name"}
return {name => params->{name}};
};
It's possible to let the client choose which serializer to use. For
this, use the C<mutable> serializer, and an appropriate serializer will be
chosen from the C<Content-Type> header.
It's also possible to return a custom error using the
L<send_error|Dancer2/send_error> keyword. When you don't use a serializer,
the C<send_error> function will take a string as first parameter (the
message), and an optional HTTP code. When using a serializer, the message
can be a string, an arrayref or a hashref:
get '/hello/:name' => sub {
if (...) {
send_error("you can't do that");
# or
send_error({reason => 'access denied', message => "no"});
}
};
The content of the error will be serialized using the appropriate
serializer.
=head1 DANCER ON THE STAGE: DEPLOYMENT
=head2 Running stand-alone
At the simplest, your Dancer2 app can run standalone, operating as its own
webserver using L<HTTP::Server::PSGI>.
Simply fire up your app:
$ perl bin/app.pl
>> Listening on 0.0.0.0:3000
== Entering the dance floor ...
Point your browser at it, and away you go!
This option can be useful for small personal web apps or internal apps, but
if you want to make your app available to the world, it probably won't suit
you.
=head2 Auto Reloading with Plack and Shotgun
To edit your files without the need to restart the webserver on each file
change, simply start your Dancer2 app using L<plackup> and
L<Plack::Loader::Shotgun>:
$ plackup -L Shotgun bin/app.pl
HTTP::Server::PSGI: Accepting connections at http://0:5000/
Point your browser at it. Files can now be changed in your favorite editor
and the browser needs to be refreshed to see the saved changes.
Please note that this is not recommended for production for performance
reasons. This is the Dancer2 replacement solution of the old Dancer
experimental C<auto_reload> option.
On Windows, Shotgun loader is known to cause huge memory leaks in a
fork-emulation layer. If you are aware of this and still want to run the
loader, please use the following command:
> set PLACK_SHOTGUN_MEMORY_LEAK=1 && plackup -L Shotgun bin\app.pl
HTTP::Server::PSGI: Accepting connections at http://0:5000/
=head2 CGI and Fast-CGI
In providing ultimate flexibility in terms of deployment, your Dancer2 app
can be run as a simple cgi-script out-of-the-box. No additional web-server
configuration needed. Your web server should recognize .cgi files and be
able to serve Perl scripts. The Perl module L<Plack::Runner> is required.
=head3 Running on Apache (CGI and FCGI)
Start by adding the following to your apache configuration (C<httpd.conf> or
C<sites-available/*site*>):
<VirtualHost *:80>
ServerName www.example.com
DocumentRoot /srv/www.example.com/public
ServerAdmin you@example.com
<Directory "/srv/www.example.com/public">
AllowOverride None
Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
Order allow,deny
Allow from all
AddHandler cgi-script .cgi
</Directory>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ /dispatch.cgi$1 [QSA,L]
ErrorLog /var/log/apache2/www.example.com-error.log
CustomLog /var/log/apache2/www.example.com-access_log common
</VirtualHost>
Note that when using fast-cgi your rewrite rule should be:
RewriteRule ^(.*)$ /dispatch.fcgi$1 [QSA,L]
Here, the mod_rewrite magic for Pretty-URLs is directly put in Apache's
configuration. But if your web server supports C<.htaccess> files, you can
drop those lines in a C<.htaccess> file.
To check if your server supports mod_rewrite type C<apache2 -l> to list
modules. To enable C<mod_rewrite> on Debian or Ubuntu, run C<a2enmod rewrite>. Place
following code in a file called C<.htaccess> in your application's root folder:
# BEGIN dancer application htaccess
RewriteEngine On
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteRule (.*) /dispatch.cgi$1 [L]
# END dancer application htaccess
Now you can access your Dancer2 application URLs as if you were using the
embedded web server:
http://localhost/
This option is a no-brainer, easy to setup, low maintenance but serves
requests slower than all other options.
You can use the same technique to deploy with FastCGI, by just changing the
line:
AddHandler cgi-script .cgi
to:
AddHandler fastcgi-script .fcgi
Of course remember to update your rewrite rules, if you have set any:
RewriteRule (.*) /dispatch.fcgi$1 [L]
=head4 Running under an appdir
If you want to deploy multiple applications under the same C<VirtualHost>
(using one application per directory, for example) you can use the following
example Apache configuration.
This example uses the FastCGI dispatcher that comes with Dancer2, but you
should be able to adapt this to use any other way of deployment described in
this guide. The only purpose of this example is to show how to deploy
multiple applications under the same base directory/C<VirtualHost>.
<VirtualHost *:80>
ServerName localhost
DocumentRoot "/path/to/rootdir"
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
<Directory "/path/to/rootdir">
AllowOverride None
Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
Order allow,deny
Allow from all
AddHandler fastcgi-script .fcgi
</Directory>
RewriteRule /App1(.*)$ /App1/public/dispatch.fcgi$1 [QSA,L]
RewriteRule /App2(.*)$ /App2/public/dispatch.fcgi$1 [QSA,L]
...
RewriteRule /AppN(.*)$ /AppN/public/dispatch.fcgi$1 [QSA,L]
</VirtualHost>
Of course, if your Apache configuration allows that, you can put the
RewriteRules in a .htaccess file directly within the application's
directory, which lets you add a new application without changing the Apache
configuration.
=head3 Running on lighttpd (CGI)
To run as a CGI app on lighttpd, just create a soft link to the C<dispatch.cgi>
script (created when you run C<dancer -a MyApp>) inside your system's C<cgi-bin>
folder. Make sure C<mod_cgi> is enabled.
ln -s /path/to/MyApp/public/dispatch.cgi /usr/lib/cgi-bin/mycoolapp.cgi
=head3 Running on lighttpd (FastCGI)
Make sure C<mod_fcgi> is enabled. You also must have L<FCGI> installed.
This example configuration uses TCP/IP:
$HTTP["url"] == "^/app" {
fastcgi.server += (
"/app" => (
"" => (
"host" => "127.0.0.1",
"port" => "5000",
"check-local" => "disable",
)
)
)
}
Launch your application:
plackup -s FCGI --port 5000 bin/app.pl
This example configuration uses a socket:
$HTTP["url"] =~ "^/app" {
fastcgi.server += (
"/app" => (
"" => (
"socket" => "/tmp/fcgi.sock",
"check-local" => "disable",
)
)
)
}
Launch your application:
plackup -s FCGI --listen /tmp/fcgi.sock bin/app.pl
=head2 Plack middlewares
If you want to use Plack middlewares, you need to enable them using
L<Plack::Builder> as such:
# in app.psgi or any other handler
use Dancer2;
use MyWebApp;
use Plack::Builder;
builder {
enable 'Deflater';
enable 'Session', store => 'File';
enable 'Debug', panels => [ qw<DBITrace Memory Timer> ];
dance;
};
The nice thing about this setup is that it will work seamlessly through
Plack or through the internal web server.
# load dev web server (without middlewares)
perl -Ilib app.psgi
# load plack web server (with middlewares)
plackup -I lib app.psgi
You do not need to provide different files for either server.
=head3 Path-based middlewares
If you want to set up a middleware for a specific path, you can do that using
L<Plack::Builder> which uses L<Plack::App::URLMap>:
# in your app.psgi or any other handler
use Dancer2;
use MyWebApp;
use Plack::Builder;
my $special_handler = sub { ... };
builder {
mount '/' => dance;
mount '/special' => $special_handler;
};
=head3 Running on Perl web servers with plackup
A number of Perl web servers supporting PSGI are available on CPAN:
=over 4
=item L<Starman|http://search.cpan.org/dist/Starman/>
C<Starman> is a high performance web server, with support for preforking,
signals, multiple interfaces, graceful restarts and dynamic worker pool
configuration.
=item L<Twiggy|http://search.cpan.org/dist/Twiggy/>
C<Twiggy> is an C<AnyEvent> web server, it's light and fast.
=item L<Corona|http://search.cpan.org/dist/Corona/>
C<Corona> is a C<Coro> based web server.
=back
To start your application, just run plackup (see L<Plack> and specific
servers above for all available options):
$ plackup bin/app.pl
$ plackup -E deployment -s Starman --workers=10 -p 5001 -a bin/app.pl
As you can see, the scaffolded Perl script for your app can be used as a
PSGI startup file.
=head4 Enabling content compression
Content compression (gzip, deflate) can be easily enabled via a Plack
middleware (see L<Plack/Plack::Middleware>): L<Plack::Middleware::Deflater>.
It's a middleware to encode the response body in gzip or deflate, based on the
C<Accept-Encoding> HTTP request header.
Enable it as you would enable any Plack middleware. First you need to
install L<Plack::Middleware::Deflater>, then in the handler (usually
F<app.psgi>) edit it to use L<Plack::Builder>, as described above:
use Dancer2;
use MyWebApp;
use Plack::Builder;
builder {
enable 'Deflater';
dance;
};
To test if content compression works, trace the HTTP request and response
before and after enabling this middleware. Among other things, you should
notice that the response is gzip or deflate encoded, and contains a header
C<Content-Encoding> set to C<gzip> or C<deflate>.
=head3 Running multiple apps with Plack::Builder
You can use L<Plack::Builder> to mount multiple Dancer2 applications on a
L<PSGI> webserver like L<Starman>.
Start by creating a simple app.psgi file:
use OurWiki; # first app
use OurForum; # second app
use Plack::Builder;
builder {
mount '/wiki' => OurWiki->psgi_app;
mount '/forum' => OurForum->psgi_app;
};
and now use L<Starman>
plackup -a app.psgi -s Starman
Currently this still demands the same appdir for both (default circumstance)
but in a future version this will be easier to change while staying very
simple to mount.
=head3 Running from Apache with Plack
You can run your app from Apache using PSGI (Plack), with a config like the
following:
<VirtualHost myapp.example.com>
ServerName www.myapp.example.com
ServerAlias myapp.example.com
DocumentRoot /websites/myapp.example.com
<Directory /home/myapp/myapp>
AllowOverride None
Order allow,deny
Allow from all
</Directory>
<Location />
SetHandler perl-script
PerlResponseHandler Plack::Handler::Apache2
PerlSetVar psgi_app /websites/myapp.example.com/app.pl
</Location>
ErrorLog /websites/myapp.example.com/logs/error_log
CustomLog /websites/myapp.example.com/logs/access_log common
</VirtualHost>
To set the environment you want to use for your application (production or
development), you can set it this way:
<VirtualHost>
...
SetEnv DANCER_ENVIRONMENT "production"
...
</VirtualHost>
=head3 Serving static files using L<Plack::Middleware::Static>
You can use L<Plack::Middleware::Static> to serve your static files instead of
L<Dancer2::Handler::File>. That way before hooks will not be executed for them.
This is required to make the example in
L<Sessions and logging-in|Dancer2::Cookbook/"Sessions_and_logging_in"> work.
First, we have to disable L<Dancer2::Handler::File> in the config:
route_handlers: []
Next, our C<bin/app.pl> should look similar to this:
#!/usr/bin/env perl
use Plack::Builder;
use Dancer2::FileUtils qw[ path ];
use MyApp;
builder {
enable "Plack::Middleware::Static",
path => sub { -f path('public', shift) },
root => 'public';
dance;
};
The C<path> option returns true if the requested file exists inside the C<public/>
directory. For example the file C</css/default.css> is searched for at
C<public/css/default.css>. When the file is found, L<Plack::Middleware::Static>
returns the requested file from the 'root' directory, which is in this example
the C<public/> folder.
=head2 Creating a service
You can turn your app into a proper service running in the background using one of
the following examples.
=head3 Using Ubic
L<Ubic> is an extensible perlish service manager. You can use it to start
and stop any services, automatically start them on reboots or daemon
failures, and implement custom status checks.
A basic PSGI service description (usually in C</etc/ubic/service/application>):
use parent qw(Ubic::Service::Plack);
# if your application is not installed in @INC path:
sub start {
my $self = shift;
$ENV{PERL5LIB} = '/path/to/your/application/lib';
$self->SUPER::start(@_);
}
__PACKAGE__->new(
server => 'Starman',
app => '/path/to/your/application/app.pl',
port => 5000,
user => 'www-data',
);
Run C<ubic start application> to start the service.
=head3 Using daemontools
daemontools is a collection of tools for managing UNIX services. You can use
it to easily start/restart/stop services.
A basic script to start an application: (in C</service/application/run>)
#!/bin/sh
# if your application is not installed in @INC path:
export PERL5LIB='/path/to/your/application/lib'
exec 2>&1 \
/usr/local/bin/plackup -s Starman -a /path/to/your/application/app.pl -p 5000
=head2 Running stand-alone behind a proxy / load balancer
Another option would be to run your app stand-alone as described above, but
then use a proxy or load balancer to accept incoming requests (on the
standard port 80, say) and feed them to your Dancer2 app.
This could be achieved using various software; examples would include:
=head3 Using Apache's C<mod_proxy>
You could set up a C<VirtualHost> for your web app, and proxy all requests
through to it:
<VirtualHost mywebapp.example.com:80>
ProxyPass / http://localhost:3000/
ProxyPassReverse / http://localhost:3000/
</VirtualHost>
Or, if you want your webapp to share an existing VirtualHost, you could have
it under a specified dir:
ProxyPass /mywebapp/ http://localhost:3000/
ProxyPassReverse /mywebapp/ http://localhost:3000/
It is important for you to note that the Apache2 modules C<mod_proxy> and
C<mod_proxy_http> must be enabled:
$ a2enmod proxy
$ a2enmod proxy_http
It is also important to set permissions for proxying for security purposes,
below is an example.
<Proxy *>
Order allow,deny
Allow from all
</Proxy>
=head3 Using perlbal
C<perlbal> is a single-threaded event-based server written in Perl
supporting HTTP load balancing, web serving, and a mix of the two, available
from L<http://www.danga.com/perlbal/>.
It processes hundreds of millions of requests a day just for LiveJournal,
Vox and TypePad and dozens of other "Web 2.0" applications.
It can also provide a management interface to let you see various
information on requests handled etc.
It could easily be used to handle requests for your Dancer2 apps, too.
It can be easily installed from CPAN:
perl -MCPAN -e 'install Perlbal'
Once installed, you'll need to write a configuration file. See the examples
provided with perlbal, but you'll probably want something like:
CREATE POOL my_dancers
POOL my_dancers ADD 10.0.0.10:3030
POOL my_dancers ADD 10.0.0.11:3030
POOL my_dancers ADD 10.0.0.12:3030
POOL my_dancers ADD 10.0.0.13:3030
CREATE SERVICE my_webapp
SET listen = 0.0.0.0:80
SET role = reverse_proxy
SET pool = my_dancers
SET persist_client = on
SET persist_backend = on
SET verify_backend = on
ENABLE my_webapp
=head3 Using balance
C<balance> is a simple load-balancer from Inlab Software, available from
L<http://www.inlab.de/balance.html>.
It could be used simply to hand requests to a standalone Dancer2 app. You
could even run several instances of your Dancer2 app, on the same machine or
on several machines, and use a machine running C<balance> to distribute the
requests between them, for some serious heavy traffic handling!
To listen on port 80, and send requests to a Dancer2 app on port 3000:
balance http localhost:3000
To listen on a specified IP only on port 80, and distribute requests between
multiple Dancer2 apps on multiple other machines:
balance -b 10.0.0.1 80 10.0.0.2:3000 10.0.0.3:3000 10.0.0.4:3000
=head3 Using lighttpd
You can use lighttp's C<mod_proxy>:
$HTTP["url"] =~ "/application" {
proxy.server = (
"/" => (
"application" => ( "host" => "127.0.0.1", "port" => 3000 )
)
)
}
This configuration will proxy all requests to the C</application> path to the
path C</> on localhost:3000.
=head3 Using Nginx
with Nginx:
upstream backendurl {
server unix:THE_PATH_OF_YOUR_PLACKUP_SOCKET_HERE.sock;
}
server {
listen 80;
server_name YOUR_HOST_HERE;
access_log /var/log/YOUR_ACCESS_LOG_HERE.log;
error_log /var/log/YOUR_ERROR_LOG_HERE.log info;
root YOUR_ROOT_PROJECT/public;
location / {
try_files $uri @proxy;
access_log off;
expires max;
}
location @proxy {
proxy_set_header Host $http_host;
proxy_set_header X-Forwarded-Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://backendurl;
}
}
You will need plackup to start a worker listening on a socket :
cd YOUR_PROJECT_PATH
sudo -u www plackup -E production -s Starman --workers=2 \
-l THE_PATH_OF_YOUR_PLACKUP_SOCKET_HERE.sock -a bin/app.pl
A good way to start this is to use C<daemontools> and place this line with
all environments variables in the "run" file.
=head1 NON-STANDARD STEPS
=head2 Turning off warnings
The C<warnings> pragma is already used when one loads Dancer2. However, if
you I<really> do not want the C<warnings> pragma (for example, due to an
undesired warning about use of undef values), add a C<no warnings> pragma to
the appropriate block in your module or psgi file.
=head1 AUTHOR
Dancer Core Developers
=head1 COPYRIGHT AND LICENSE
This software is copyright (c) 2014 by Alexis Sukrieh.
This is free software; you can redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.
=cut
|