/usr/share/perl5/Dancer/Introduction.pod is in libdancer-perl 1.3202+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 | package Dancer::Introduction
# ABSTRACT: A gentle introduction to Dancer
__END__
=pod
=encoding UTF-8
=head1 NAME
Dancer::Introduction - A gentle introduction to Dancer
=head1 VERSION
version 1.3202
=head1 DESCRIPTION
Dancer is a free and open source micro web application framework written in
Perl.
=head1 INSTALL
Installation of Dancer is simple:
perl -MCPAN -e 'install Dancer'
Thanks to the magic of cpanminus, if you do not have CPAN.pm configured, or just
want a quickfire way to get running, the following should work, at least on
Unix-like systems:
wget -O - http://cpanmin.us | sudo perl - Dancer
(If you don't have root access, omit the 'sudo', and cpanminus will install
Dancer and prereqs into C<~/perl5>.)
=head1 SETUP
Create a web application using the dancer script:
dancer -a MyApp
Run the web application:
cd MyApp
bin/app.pl
You can read the output of C<bin/app.pl --help> to change any settings such as
the port number.
View the web application at:
http://localhost:3000
=head1 USAGE
When Dancer is imported to a script, that script becomes a webapp, and at this
point, all the script has to do is declare a list of B<routes>. A route
handler is composed by an HTTP method, a path pattern and a code block.
C<strict> and C<warnings> pragmas are also imported with Dancer.
The code block given to the route handler has to return a string which will be
used as the content to render to the client.
Routes are defined for a given HTTP method. For each method
supported, a keyword is exported by the module.
The following is an example of a route definition. The route is defined for the
method 'get', so only GET requests will be honoured by that route:
get '/hello/:name' => sub {
# do something
return "Hello ".param('name');
};
=head2 HTTP METHODS
Here are some of the standard HTTP methods which you can use to define your
route handlers.
=over 8
=item B<GET>
The GET method retrieves information (when defining a route
handler for the GET method, Dancer automatically defines a
route handler for the HEAD method, in order to honour HEAD
requests for each of your GET route handlers).
To define a GET action, use the B<get> keyword.
=item B<POST>
The POST method is used to create a resource on the
server.
To define a POST action, use the B<post> keyword.
=item B<PUT>
The PUT method is used to update an existing resource.
To define a PUT action, use the B<put> keyword.
=item B<DELETE>
The DELETE method requests that the origin server delete
the resource identified by the Request-URI.
To define a DELETE action, use the B<del> keyword.
=back
To define a route for multiple methods you can also use the special keyword
B<any>. This example illustrates how to define a route for both GET and
POST methods:
any ['get', 'post'] => '/myaction' => sub {
# code
};
Or even, a route handler that would match any HTTP methods:
any '/myaction' => sub {
# code
};
=head2 ROUTE HANDLERS
The route action is the code reference declared. It can access parameters
through the `params' keyword, which returns a hashref.
This hashref is a merge of the route pattern matches and the request params.
You can have more details about how params are built and how to access them in
the L<Dancer::Request> documentation.
=head2 NAMED MATCHING
A route pattern can contain one or more tokens (a word prefixed with ':'). Each
token found in a route pattern is used as a named-pattern match. Any match will
be set in the params hashref.
get '/hello/:name' => sub {
"Hey ".param('name').", welcome here!";
};
Tokens can be optional, for example:
get '/hello/:name?' => sub {
"Hello there " . (param('name') || "whoever you are!");
};
=head2 WILDCARDS MATCHING
A route can contain a wildcard (represented by a '*'). Each wildcard match will
be returned in an arrayref, accessible via the `splat' keyword.
get '/download/*.*' => sub {
my ($file, $ext) = splat;
# do something with $file.$ext here
};
=head2 REGULAR EXPRESSION MATCHING
A route can be defined with a Perl regular expression.
In order to tell Dancer to consider the route as a real regexp, the route must
be defined explicitly with C<qr{}>, like the following:
get qr{/hello/([\w]+)} => sub {
my ($name) = splat;
return "Hello $name";
};
=head2 CONDITIONAL MATCHING
Routes may include some matching conditions (on the useragent and the hostname
at the moment):
get '/foo', {agent => 'Songbird (\d\.\d)[\d\/]*?'} => sub {
'foo method for songbird'
}
get '/foo' => sub {
'all browsers except songbird'
}
=head2 PREFIX
A prefix can be defined for each route handler, like this:
prefix '/home';
From here, any route handler is defined to /home/*
get '/page1' => sub {}; # will match '/home/page1'
You can unset the prefix value
prefix '/'; # or: prefix undef;
get '/page1' => sub {}; # will match '/page1'
Alternatively, to prevent you from ever forgetting to undef the prefix,
you can use lexical prefix like this:
prefix '/home' => sub {
get '/page1' => sub {}; # will match '/home/page1'
}; ## prefix reset to previous value on exit
get '/page1' => sub {}; # will match '/page1'
=head1 ACTION SKIPPING
An action can choose not to serve the current request and ask Dancer to process
the request with the next matching route.
This is done with the B<pass> keyword, like in the following example
get '/say/:word' => sub {
return pass if (params->{word} =~ /^\d+$/);
"I say a word: ".params->{word};
};
get '/say/:number' => sub {
"I say a number: ".params->{number};
};
=head2 DEFAULT ERROR PAGES
When an error is rendered (the action responded with a status code different
than 200), Dancer first looks in the public directory for an HTML file matching
the error code (eg: 500.html or 404.html).
If such a file exists, it's used to render the error, otherwise, a default
error page will be rendered on the fly.
=head2 EXECUTION ERRORS
When an error occurs during the route execution, Dancer will render an error
page with the HTTP status code 500.
It's possible either to display the content of the error message or to hide it
with a generic error page.
This is a choice left to the end-user and can be set with the
B<show_errors> setting.
Note that you can also choose to consider all warnings in your route handlers
as errors when the setting B<warnings> is set to 1.
=head1 HOOKS
=head2 Before hooks
Before hooks are evaluated before each request within the context of the
request and can modify the request and response. It's possible to define
variables which will be accessible in the action blocks with the keyword 'var'.
hook 'before' => sub {
var note => 'Hi there';
request->path_info('/foo/oversee')
};
get '/foo/*' => sub {
my ($match) = splat; # 'oversee';
vars->{note}; # 'Hi there'
};
For another example, this can be used along with session support to easily
give non-logged-in users a login page:
hook 'before' => sub {
if (!session('user') && request->path_info !~ m{^/login}) {
# Pass the original path requested along to the handler:
var requested_path => request->path_info;
request->path_info('/login');
}
};
The request keyword returns the current Dancer::Request object representing the
incoming request. See the documentation of the L<Dancer::Request> module for
details.
=head2 After hooks
C<after> hooks are evaluated after the response has been built by a route
handler, and can alter the response itself, just before it's sent to the
client.
The hook is given the response object as its first argument:
hook 'after' => sub {
my $response = shift;
$response->{content} = 'after hook got here!';
};
=head2 Before template hook
C<before_template_render> hooks are called whenever a template is going to be
processed, they are passed the tokens hash which they can alter.
hook 'before_template_render' => sub {
my $tokens = shift;
$tokens->{foo} = 'bar';
};
The tokens hash will then be passed to the template with all the modifications
performed by the hook. This is a good way to setup some global vars you like
to have in all your templates, like the name of the user logged in or a
section name.
=head1 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 write all your setting calls in the file
`appdir/config.yml'. For this, you must have installed the YAML module, and of
course, write the conffile 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 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 --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 load
You can use the load method to include additional routes into your application:
get '/go/:value', sub {
# foo
};
load 'more_routes.pl';
# then, in the file more_routes.pl:
get '/yes', sub {
'orly?';
};
B<load> is just a wrapper for B<require>, but you can also specify a list of
routes files:
load 'login_routes.pl', 'session_routes.pl', 'misc_routes.pl';
=head2 Accessing configuration data
A Dancer application can access the information from its config file easily with
the config keyword:
get '/appname' => sub {
return "This is " . config->{appname};
};
=head1 Importing just the syntax
If you want to use more complex file hierarchies, you can import just the
syntax of Dancer.
package App;
use Dancer; # App may contain generic routes
use App::User::Routes; # user-related routes
Then in App/User/Routes.pm:
use Dancer ':syntax';
get '/user/view/:id' => sub {
...
};
=head1 LOGGING
It's possible to log messages sent by the application. In the current version,
only one method is possible for logging messages but future releases may add
additional logging methods, for instance logging to syslog.
In order to enable the logging system for your application, you first have to
start the logger engine in your config.yml
logger: 'file'
Then you can choose which kind of messages you want to actually log:
log: 'debug' # will log debug, warning, error and info messages
log: 'info' # will log info, warning and error messages
log: 'warning' # will log warning and error messages
log: 'error' # will log error messages
A directory 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).
To log messages, use the debug, info, warning and error functions. For
instance:
debug "This is a debug message";
=head1 USING TEMPLATES
=head1 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', for instance if
your templates are located in the 'templates' directory, do the following:
set views => path(dirname(__FILE__), 'templates');
By default, the internal template engine is used (L<Dancer::Template::Simple>)
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 Dancer configures
the Template::Toolkit engine to use <% %> brackets instead of its default
[% %] brackets, although you can change this in your config file.
All views must have a '.tt' extension. This may change in the future.
In order to render a view, just call the '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 the request, session and route params are automatically
accessible in the view, named request, session and params):
use Dancer;
use Template;
get '/hello/:name' => sub {
template 'hello' => { number => 42 };
};
And the appdir/views/hello.tt view can contain the following code:
<html>
<head></head>
<body>
<h1>Hello <% params.name %></h1>
<p>Your lucky number is <% number %></p>
<p>You are using <% request.user_agent %></p>
<% IF session.user %>
<p>You're logged in as <% session.user %></p>
<% END %>
</body>
</html>
=head2 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. Any tokens that you defined when you called the 'template'
keyword are available in the layouts, as well as the standard session,
request, and params tokens. This allows you to insert per-page content into
the HTML boilerplate, such as page titles, current-page tags for navigation,
etc.
Here is an example of a layout: views/layouts/main.tt:
<html>
<head><% page_title %></head>
<body>
<div id="header">
...
</div>
<div id="content">
<% content %>
</div>
</body>
</html>
This layout can be used like the following:
use Dancer;
set layout => 'main';
get '/' => sub {
template 'index' => { page_title => "Your website Homepage" };
};
Of course, if a layout is set, it can also be disabled for a specific action,
like the following:
use Dancer;
set layout => 'main';
get '/nolayout' => sub {
template 'some_ajax_view',
{ tokens_var => "42" },
{ layout => 0 };
};
=head1 STATIC FILES
=head2 STATIC DIRECTORY
Static files are served from the ./public directory. You can specify a
different location by setting the 'public' option:
set public => path(dirname(__FILE__), 'static');
Note that the public directory name is not included in the URL. A file
./public/css/style.css is made available as example.com/css/style.css.
=head2 STATIC FILE FROM A ROUTE HANDLER
It's possible for a route handler to send a static file, as follows:
get '/download/*' => sub {
my $params = shift;
my ($file) = @{ $params->{splat} };
send_file $file;
};
Or even if you want your index page to be a plain old index.html file, just do:
get '/' => sub {
send_file '/index.html'
};
=head1 SETTINGS
It's possible to change quite every parameter of the application via the
settings mechanism.
A setting is key/value pair assigned by the keyword B<set>:
set setting_name => 'setting_value';
More usefully, settings can be defined in a YAML configuration file.
Environment-specific settings can also be defined in environment-specific files
(for instance, you might want extra logging in development). See the cookbook for examples.
See L<Dancer::Config> for complete details about supported settings.
=head1 SERIALIZERS
When writing a webservice, data serialization/deserialization is a common issue
to deal with. Dancer can automatically handle that for you, via a serializer.
When setting up a serializer, a new behaviour is authorized for any route
handler you define: any response that is a reference will be rendered as a
serialized string, via the current serializer.
Here is an example of a route handler that will return a HashRef
use Dancer;
set serializer => 'JSON';
get '/user/:id/' => sub {
{ foo => 42,
number => 100234,
list => [qw(one two three)],
}
};
As soon as the content is a reference - and a serializer is set, which is not
the case by default - Dancer renders the response via the current
serializer.
Hence, with the JSON serializer set, the route handler above would result in a
content like the following:
{"number":100234,"foo":42,"list":["one","two","three"]}
The following serializers are available, be aware they dynamically depend on
Perl modules you may not have on your system.
=over 4
=item B<JSON>
requires L<JSON>
=item B<YAML>
requires L<YAML>
=item B<XML>
requires L<XML::Simple>
=item B<Mutable>
will try to find the appropriate serializer using the B<Content-Type> and
B<Accept-type> header of the request.
=back
=head1 EXAMPLE
This is a possible webapp created with Dancer:
#!/usr/bin/perl
# make this script a webapp
use Dancer;
# declare routes/actions
get '/' => sub {
"Hello World";
};
get '/hello/:name' => sub {
"Hello ".param('name');
};
# run the webserver
Dancer->dance;
=head1 AUTHOR
Dancer Core Developers
=head1 COPYRIGHT AND LICENSE
This software is copyright (c) 2010 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
|