/usr/share/perl5/Dancer/Cookbook.pod is in libdancer-perl 1.3120+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 | =head1 NAME
Dancer::Cookbook - a quick-start guide to the Dancer web framework
=head1 DESCRIPTION
A quick-start guide with examples to get you up and running with the Dancer web
framework.
=head1 BEGINNER'S DANCE
=head2 Your first Dancer web app
Dancer 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 Dancer;
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
(or the name of the machine you ran it on, if it's not your local system),
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>
- more on that later.
Note that you don't need to use the C<strict> and C<warnings> pragma, they are
already loaded by Dancer. (If you don't want the C<warnings> pragma (which can
lead to undesired warnings about use of undef values, for example), then set the
L<import_warnings|Dancer::Config/import_warnings> setting to a false value.
=head2 Starting a Dancer project
The first simple example is fine for trivial projects, but for anything more
complex, you'll want a more maintainable solution - enter the C<dancer> helper
script, which will build the framework of your application with a single
command:
$ dancer -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.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, a script to
start it - or to run your web app via Plack/PSGI - more on that later.
=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. /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 '/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 /myaction:
any '/myaction' => sub {
# code
}
The following will match GET or POST requests to /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|Dancer/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 HTTP 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|Dancer/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|Dancer/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 hooks - processed before a request
A before L<hook|Dancer/hook> declares code which should be handled before
a request is passed to the appropriate route.
hook 'before' => sub {
var note => 'Hi there';
request->path_info('/foo/oversee')
};
get '/foo/*' => sub {
my ($match) = splat; # 'oversee';
vars->{note}; # 'Hi there'
};
The above declares a before hook which uses C<var> to set a variable which
will later be available within the route handler, then amends the path of the
request to C</foo/oversee>; this means that, whatever path was requested, it
will be treated as though the path requested was C</foo/oversee>.
=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 as such:
You tried to reach <% path %>, but it is unavailable at the moment.
Please try again or contact us at our email at <...>.
=head2 Using the auto_page feature for automatic route creation
For simple "static" pages, you can simply enable the C<auto_page> config
setting; this means that you need not declare a route handler for those pages;
if a request is for C</foo/bar>, Dancer 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|Dancer::Config/"auto_page">.
=head2 Why should I use the Ajax plugin
As an Ajax query is just a 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<Dancer::Plugin::Ajax> plugin) instead of a simple
C<get>.
Let's say you have a path like '/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 a 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 to 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 Dancer ':syntax';
use myapp::admin;
prefix undef;
get '/' => sub {...};
1;
package myapp::admin;
use Dancer ':syntax';
prefix '/admin';
get '/' => sub {...};
1;
The following routes will be generated for us:
- get /
- get /admin/
- head /
- head /admin/
=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:
config file, add:
session: Simple
The L<Dancer::Session::Simple> backend implements very simple in-memory session
storage. This will be fast and useful for testing, but sessions do not persist
between restarts of your app.
You can also use the L<Dancer::Session::YAML> backend included with Dancer,
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';
(Controlling settings is best done from your config file, though). 'YAML' in
the example is the session backend to use; this is shorthand for
L<Dancer::Session::YAML>. There are other session backends you may wish to use,
for instance L<Dancer::Session::Memcache>, but the YAML backend is a simple and
easy to use example which stores session data in a YAML file in sessions).
You can then use the L<session|Dancer/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->{varname}
=head3 Controlling where sessions are stored
For disc-based session back ends like L<Dancer::Session::YAML>,
L<Dancer::Session::Storable> etc, session files are written to the session dir
specified by the C<session_dir> setting, which defaults to C<appdir/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_dir: /tmp/dancer-sessions
If the directory you specify does not exist, Dancer will attempt to create it
for you.
=head3 Destroying a session
When you're done with your session, you can destroy it:
session->destroy
=head2 Sessions and logging in
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 L<hook|Dancer/hook> to check their session:
hook 'before' => sub {
if (! session('user') && request->path_info !~ m{^/login}) {
var requested_path => request->path_info;
request->path_info('/login');
}
};
get '/login' => sub {
# Display a login page; the original URL they requested is available as
# vars->{requested_path}, so could be put in a hidden field in the form
template 'login', { path => vars->{requested_path} };
};
post '/login' => sub {
# Validate the username and password they supplied
if (params->{user} eq 'bob' && params->{pass} eq 'letmein') {
session user => params->{user};
redirect params->{path} || '/';
} else {
redirect '/login?failed=1';
}
};
In your login page template, you'll want a text field named user, a password
field named pass, and a hidden field named path, which will be populated with
the path originally requested, so that it's sent back in the POST submission,
and can be used by the post route to redirect onwards to the page originally
requested once you're logged in.
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<Dancer::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
=head2 Using templates - views 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. Dancer makes this easy.
Your route handlers can use the L<template|Dancer/template> keyword to render
templates.
=head3 Views
It's possible to render the action's content with a template, this is called a
view. The `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<Dancer::Template::Simple> is used,
but you may want to upgrade to Template::Toolkit. If you do so, you have to
enable this engine in your settings as explained in
L<Dancer::Template::TemplateToolkit>. If you do so, you'll also have to
import the L<Template> module in your application code.
Note that, by default, Dancer configures the Template::Toolkit engine to use
C<<% %>> brackets instead of its default C<[% %]> brackets. You can change this
by using the following in your config file:
template: template_toolkit
engines:
template_toolkit:
start_tag: '[%'
stop_tag: '%]'
All views must have a '.tt' extension. This may change in the future.
In order to render a view, just call the C<template|Dancer/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 '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 %>
<% 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<Dancer::Template::Abstract>).
=head3 Layouts
A layout is a special view, located in the 'layouts' directory (inside the views
directory) which must have a token named '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 the 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 (B</>), you can use a
before_template_render hook instead of hardcoding the path to 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
=head3 template and unicode
If you use L<Plack> and have some unicode problem with your Dancer 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.yml will look like this:
charset: UTF-8
engines:
template_toolkit:
ENCODING: utf8
=head3 TT's WRAPPER directive in Dancer (META variables, SETs)
Dancer already provides a WRAPPER-like ability, which we call a "layout". The
reason we do not use TT's WRAPPER (which also makes it 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 Dancer
You can do this by simply commenting (or removing) the C<layout> configuration
in the F<config.yml> file.
=item * Use 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 who's your wrapper
# in config.yml
# ...
engines:
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 Dancer 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 dance() method.
Other ways are possible, you can define all your settings in the file
`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.yml
file.
The better way is to have one 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>
commandline 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 from your app
A Dancer application can use the '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 :)
=head2 Accessing configuration information from a separate script
You may well 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 config.yml, but chances are that this is not convenient.
Use Dancer instead. Without any ado, magic or too big jumps, you can use the
values from config.yml and some additional default values:
# bin/script1.pl
use Dancer ':script';
print "template:".config->{template}."\n"; #simple
print "log:".config->{log}."\n"; #undef
Note that config->{log} should result undef error on a default scaffold since
you did not load the environment and in the default scaffold log is defined in
the environment and not in config.yml. Hence undef.
If you want to load an environment you need to tell Dancer where to look for it.
One way to do so, is to tell Dancer where the webapp lives. From there Dancer
deducts where the config.yml file is (typically $webapp/config.yml).
# bin/script2.pl
use FindBin;
use Cwd qw/realpath/;
use Dancer ':script';
#tell the Dancer where the app lives
my $appdir=realpath( "$FindBin::Bin/..");
Dancer::Config::setting('appdir',$appdir);
Dancer::Config::load();
#getter
print "environment:".config->{environment}."\n"; #development
print "log:".config->{log}."\n"; #value from development environment
By default Dancer loads development environment (typically
$webapp/environment/development.yml). In contrast to the example before, you
do have a value from the development environment (environment/development.yml)
now. Also note that in the above example Cwd and FindBin are used. They are
likely to be already loaded by Dancer 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.:
Dancer::Config::setting('appdir','/path/to/app/dir');
If you want to load an environment other than the default, try this:
# bin/script2.pl
use Dancer ':script';
#tell the Dancer where the app lives
Dancer::Config::setting('appdir','/path/to/app/dir');
#which environment to load
config->{environment}='production';
Dancer::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 straightforward
like we do above with config->{environment}='production'. Of course, this value
does not get written in any file; it only lives in memory and 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 Dancer itself.
To start logging, select the logging engine you wish to use with the C<logger>
setting; Dancer 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.yml:
logger: 'file'
Then you can choose which kind of messages you want to actually log:
log: 'core' # will log all messages, including messages from
# Dancer itself
log: 'debug' # will log debug, info, warning and error messages
log: 'info' # will log info, warning and error messages
log: 'warning' # will log warning and error messages
log: 'error' # will log error messages
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|Dancer/debug>, L<warning|Dancer/warning>,
L<error|Dancer/error> or L<info|Dancer/info> with your message:
debug "This is a debug message from my app.";
=head1 RESTING
=head2 Writing a REST application
With Dancer, it's easy to write REST applications. Dancer 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.yml:
serializer: JSON
Or right in your code:
set serializer => 'JSON';
From now, all hash ref or array ref 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 he want to use. For
this, use the B<mutable> serializer, and an appropriate serializer will be
chosen from the B<Content-Type> header.
It's also possible to return a custom error, using the
L<send_error|Dancer/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.
=head2 Deploying your Dancer applications
For examples on deploying your Dancer applications (including standalone, behind
proxy/load-balancing software, and using common web servers including Apache to
run via CGI/FastCGI etc, see L<Dancer::Deployment>.
=head1 DANCER ON THE STAGE: DEPLOYMENT
=head2 Plack middlewares
If you deploy with Plack and use some Plack middlewares, you can enable them
directly from Dancer's configuration files.
=head3 Generic middlewares
To enable middlewares in Dancer, you just have to set the plack_middlewares
setting like the following:
set plack_middlewares => [
[ 'SomeMiddleware' => qw(some options for somemiddleware) ],
];
For instance, if you want to enable L<Plack::Middleware::Debug> in your Dancer
application, all you have to do is to set C<plack_middlewares> like that:
set plack_middlewares => [
[ 'Debug' => ( 'panels' => [qw(DBITrace Memory Timer)] ) ],
];
Of course, you can also put this configuration into your config.yml file, or
even in your environment configuration files:
# environments/development.yml
...
plack_middlewares:
-
- Debug # first element of the array is the name of the middleware
- panels # following elements are the configuration ofthe middleware
-
- DBITrace
- Memory
- Timer
=head3 Path-based middlewares
If you want to setup a middleware for a specific path, you can do that using
C<plack_middlewares_map>. You'll need L<Plack::App::URLMap> to do that.
plack_middlewares_map:
'/': ['Debug']
'/timer': ['Timer'],
=head1 AUTHORS
Dancer contributors - see AUTHORS file.
|