.\" Automatically generated by Pod::Man 4.14 (Pod::Simple 3.40) .\" .\" Standard preamble: .\" ======================================================================== .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" Set up some character translations and predefined strings. \*(-- will .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left .\" double quote, and \*(R" will give a right double quote. \*(C+ will .\" give a nicer C++. Capital omega is used to do unbreakable dashes and .\" therefore won't be available. \*(C` and \*(C' expand to `' in nroff, .\" nothing in troff, for use with C<>. .tr \(*W- .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' .ie n \{\ . ds -- \(*W- . ds PI pi . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch . ds L" "" . ds R" "" . ds C` "" . ds C' "" 'br\} .el\{\ . ds -- \|\(em\| . ds PI \(*p . ds L" `` . ds R" '' . ds C` . ds C' 'br\} .\" .\" Escape single quotes in literal strings from groff's Unicode transform. .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" .\" If the F register is >0, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .\" .\" Avoid warning from groff about undefined register 'F'. .de IX .. .nr rF 0 .if \n(.g .if rF .nr rF 1 .if (\n(rF:(\n(.g==0)) \{\ . if \nF \{\ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . if !\nF==2 \{\ . nr % 0 . nr F 2 . \} . \} .\} .rr rF .\" ======================================================================== .\" .IX Title "Dancer2::Manual 3pm" .TH Dancer2::Manual 3pm "2021-03-13" "perl v5.32.1" "User Contributed Perl Documentation" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .if n .ad l .nh .SH "NAME" Dancer2::Manual \- A gentle introduction to Dancer2 .SH "VERSION" .IX Header "VERSION" version 0.300005 .SH "DESCRIPTION" .IX Header "DESCRIPTION" Dancer2 is a free and open source web application framework written in Perl. .PP It's a complete rewrite of Dancer, based on Moo and using a more robust and extensible fully-OO design. .PP It's designed to be powerful and flexible, but also easy to use \- getting up and running with your web app is trivial, and an ecosystem of adaptors for common template engines, session storage, logging methods, serializers, and plugins to make common tasks easy means you can do what you want to do, your way, easily. .SH "INSTALL" .IX Header "INSTALL" Installation of Dancer2 is simple, using your favourite method to install from \&\s-1CPAN,\s0 e.g.: .PP .Vb 1 \& perl \-MCPAN \-e \*(Aqinstall Dancer2\*(Aq .Ve .PP Thanks to the magic of cpanminus, if you do not have \s-1CPAN\s0.pm configured, or just want a quickfire way to get running, the following should work, at least on Unix-like systems: .PP .Vb 1 \& wget \-O \- http://cpanmin.us | sudo perl \- Dancer2 .Ve .PP (If you don't have root access, omit the 'sudo', and cpanminus will install Dancer2 and prereqs into \f(CW\*(C`~/perl5\*(C'\fR.) .PP Dancer2 is also available as a package from the package repository of several distributions, for example on Debian/Ubuntu you should be able to just: .PP .Vb 1 \& apt\-get install libdancer2\-perl .Ve .PP Do be aware, though, that distribution-packaged versions sometimes lag behind the most recent version on \s-1CPAN.\s0 .SH "BOOTSTRAPPING A NEW APP" .IX Header "BOOTSTRAPPING A NEW APP" Create a web application using the dancer script: .PP .Vb 10 \& $ dancer2 \-a MyApp && cd MyApp \& + MyApp \& + MyApp/config.yml \& + MyApp/Makefile.PL \& + MyApp/MANIFEST.SKIP \& + MyApp/.dancer \& + MyApp/cpanfile \& + MyApp/bin \& + MyApp/bin/app.psgi \& + MyApp/environments \& + MyApp/environments/development.yml \& + MyApp/environments/production.yml \& + MyApp/lib \& + MyApp/lib/MyApp.pm \& + MyApp/public \& + MyApp/public/favicon.ico \& + MyApp/public/500.html \& + MyApp/public/dispatch.cgi \& + MyApp/public/404.html \& + MyApp/public/dispatch.fcgi \& + MyApp/public/css \& + MyApp/public/css/error.css \& + MyApp/public/css/style.css \& + MyApp/public/images \& + MyApp/public/images/perldancer.jpg \& + MyApp/public/images/perldancer\-bg.jpg \& + MyApp/public/javascripts \& + MyApp/public/javascripts/jquery.js \& + MyApp/t \& + MyApp/t/001_base.t \& + MyApp/t/002_index_route.t \& + MyApp/views \& + MyApp/views/index.tt \& + MyApp/views/layouts \& + MyApp/views/layouts/main.tt .Ve .PP 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. A default skeleton is used to bootstrap the new application, but you can use the \f(CW\*(C`\-s\*(C'\fR option to provide another skeleton. For example: .PP .Vb 1 \& $ dancer2 \-a MyApp \-s ~/mydancerskel .Ve .PP For an example of a skeleton directory check the default one available in the \f(CW\*(C`share/\*(C'\fR directory of your Dancer2 distribution. .PP (In what follows we will refer to the directory in which you have created your Dancer2 application \*(-- \fIe.g.,\fR what \f(CW\*(C`MyApp\*(C'\fR was above \*(-- as the \&\f(CW\*(C`appdir\*(C'\fR.) .PP Because Dancer2 is a \s-1PSGI\s0 web application framework, you can use the \&\f(CW\*(C`plackup\*(C'\fR tool (provided by Plack) for launching the application: .PP .Vb 1 \& plackup \-p 5000 bin/app.psgi .Ve .PP View the web application at: .PP .Vb 1 \& http://localhost:5000 .Ve .SH "USAGE" .IX Header "USAGE" When Dancer2 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 \fBroutes\fR. A route handler is composed by an \s-1HTTP\s0 method, a path pattern and a code block. \f(CW\*(C`strict\*(C'\fR, \f(CW\*(C`warnings\*(C'\fR and \f(CW\*(C`utf8\*(C'\fR pragmas are also imported with Dancer2. .PP 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. .PP Routes are defined for a given \s-1HTTP\s0 method. For each method supported, a keyword is exported by the module. .SS "\s-1HTTP\s0 Methods" .IX Subsection "HTTP Methods" Here are some of the standard \s-1HTTP\s0 methods which you can use to define your route handlers. .IP "\(bu" 4 \&\fB\s-1GET\s0\fR The \s-1GET\s0 method retrieves information, and is the most common .Sp \&\s-1GET\s0 requests should be used for typical \*(L"fetch\*(R" requests \- retrieving information. They should not be used for requests which change data on the server or have other effects. .Sp When defining a route handler for the \s-1GET\s0 method, Dancer2 automatically defines a route handler for the \s-1HEAD\s0 method (in order to honour \s-1HEAD\s0 requests for each of your \s-1GET\s0 route handlers). .Sp To define a \s-1GET\s0 action, use the get keyword. .IP "\(bu" 4 \&\fB\s-1POST\s0\fR The \s-1POST\s0 method is used to create a resource on the server. .Sp To define a \s-1POST\s0 action, use the post keyword. .IP "\(bu" 4 \&\fB\s-1PUT\s0\fR The \s-1PUT\s0 method is used to replace an existing resource. .Sp To define a \s-1PUT\s0 action, use the put keyword. .Sp a \s-1PUT\s0 request should replace the existing resource with that specified \- for instance \- if you wanted to just update an email address for a user, you'd have to specify all attributes of the user again; to make a partial update, a \s-1PATCH\s0 request is used. .IP "\(bu" 4 \&\fB\s-1PATCH\s0\fR The \s-1PATCH\s0 method updates some attributes of an existing resource. .Sp To define a \s-1PATCH\s0 action, use the patch keyword. .IP "\(bu" 4 \&\fB\s-1DELETE\s0\fR The \s-1DELETE\s0 method requests that the origin server delete the resource identified by the Request-URI. .Sp To define a \s-1DELETE\s0 action, use the del keyword. .PP \fIHandling multiple \s-1HTTP\s0 request methods\fR .IX Subsection "Handling multiple HTTP request methods" .PP Routes can use \f(CW\*(C`any\*(C'\fR to match all, or a specified list of \s-1HTTP\s0 methods. .PP The following will match any \s-1HTTP\s0 request to the path \f(CW\*(C`/myaction\*(C'\fR: .PP .Vb 3 \& any \*(Aq/myaction\*(Aq => sub { \& # code \& } .Ve .PP The following will match \s-1GET\s0 or \s-1POST\s0 requests to \f(CW\*(C`/myaction\*(C'\fR: .PP .Vb 3 \& any [\*(Aqget\*(Aq, \*(Aqpost\*(Aq] => \*(Aq/myaction\*(Aq => sub { \& # code \& }; .Ve .PP For convenience, any route which matches \s-1GET\s0 requests will also match \s-1HEAD\s0 requests. .SS "Route Handlers" .IX Subsection "Route Handlers" The route action is the code reference declared. It can access parameters through the specific route_parameters, query_parameters, and body_parameters keywords, which return a Hash::MultiValue object. This hashref is a merge of the route pattern matches and the request params. .PP You can find more details about how params are built and how to access them in the Dancer2::Core::Request documentation. .PP \fIDeclaring Routes\fR .IX Subsection "Declaring Routes" .PP To control what happens when a web request is received by your webapp, you'll need to declare \f(CW\*(C`routes\*(C'\fR. A route declaration indicates which \s-1HTTP\s0 method(s) it is valid for, the path it matches (e.g. \f(CW\*(C`/foo/bar\*(C'\fR), and a coderef to execute, which returns the response. .PP .Vb 3 \& get \*(Aq/hello/:name\*(Aq => sub { \& return "Hi there " . route_parameters\->get(\*(Aqname\*(Aq); \& }; .Ve .PP The above route specifies that, for \s-1GET\s0 requests to \f(CW\*(C`/hello/...\*(C'\fR, the code block provided should be executed. .PP \fIRetrieving request parameters\fR .IX Subsection "Retrieving request parameters" .PP The query_parameters, route_parameters, and body_parameters keywords provide a Hash::MultiValue result from the three different parameters. .PP \fINamed matching\fR .IX Subsection "Named matching" .PP 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 route parameters. .PP .Vb 3 \& get \*(Aq/hello/:name\*(Aq => sub { \& return "Hey " . route_parameters\->get(\*(Aqname\*(Aq) . ", welcome here!"; \& }; .Ve .PP Tokens can be optional, for example: .PP .Vb 4 \& get \*(Aq/hello/:name?\*(Aq => sub { \& my $name = route_parameters\->get(\*(Aqname\*(Aq) // \*(AqWhoever you are\*(Aq; \& return "Hello there, $name"; \& }; .Ve .PP \fINamed matching with type constraints\fR .IX Subsection "Named matching with type constraints" .PP Type constraints can be added to tokens. .PP .Vb 4 \& get \*(Aq/user/:id[Int]\*(Aq => sub { \& # matches /user/34 but not /user/jamesdean \& my $user_id = route_parameters\->get(\*(Aqid\*(Aq); \& }; \& \& get \*(Aq/user/:username[Str]\*(Aq => sub { \& # matches /user/jamesdean but not /user/34 since that is caught \& # by previous route \& my $username = route_parameters\->get(\*(Aqusername\*(Aq); \& }; .Ve .PP You can even use type constraints to add a regexp check: .PP .Vb 4 \& get \*(Aq/book/:date[StrMatch[qr{\ed\ed\ed\ed\-\ed\ed\-\ed\ed}]]\*(Aq => sub { \& # matches /book/2014\-02\-04 \& my $date = route_parameters\->get(\*(Aqdate\*(Aq); \& }; .Ve .PP The default type library is Dancer2::Core::Types but any type library built using Type::Tiny's Type::Library can be used instead. If you'd like to use a different default type library you must declare it in the configuration file, for example: .PP .Vb 1 \& type_library: My::Type::Library .Ve .PP Alternatively you can specify the type library in which the type is defined as part of the route definition: .PP .Vb 3 \& get \*(Aq/user/:username[My::Type::Library::Username]\*(Aq => sub { \& my $username = route_parameters\->get(\*(Aqusername\*(Aq); \& }; .Ve .PP This will load \f(CW\*(C`My::Type::Library\*(C'\fR and from it use the type \f(CW\*(C`Username\*(C'\fR. This allows types to be used that are not part of the type library defined by config's \&\f(CW\*(C`type_library\*(C'\fR. .PP More complex constructs are allowed such as: .PP .Vb 3 \& get \*(Aq/some/:thing[Int|MyDate]\*(Aq => sub { \& ...; \& }; .Ve .PP See \*(L"lookup($name)\*(R" in Type::Registry for more details. .PP \fIWildcard Matching\fR .IX Subsection "Wildcard Matching" .PP A route can contain a wildcard (represented by a \f(CW\*(C`*\*(C'\fR). Each wildcard match will be placed in a list, which the \f(CW\*(C`splat\*(C'\fR keyword returns. .PP .Vb 4 \& get \*(Aq/download/*.*\*(Aq => sub { \& my ($file, $ext) = splat; \& # do something with $file.$ext here \& }; .Ve .PP An extensive, greedier wildcard represented by \f(CW\*(C`**\*(C'\fR (A.K.A. \*(L"megasplat\*(R") can be used to define a route. The additional path is broken down and returned as an arrayref: .PP .Vb 4 \& get \*(Aq/entry/*/tags/**\*(Aq => sub { \& my ( $entry_id, $tags ) = splat; \& my @tags = @{$tags}; \& }; .Ve .PP The \f(CW\*(C`splat\*(C'\fR keyword in the above example for the route \fI/entry/1/tags/one/two\fR would set \f(CW$entry_id\fR to \f(CW1\fR and \f(CW$tags\fR to \f(CW\*(C`[\*(Aqone\*(Aq, \*(Aqtwo\*(Aq]\*(C'\fR. .PP \fIMixed named and wildcard matching\fR .IX Subsection "Mixed named and wildcard matching" .PP A route can combine named (token) matching and wildcard matching. This is useful when chaining actions: .PP .Vb 4 \& get \*(Aq/team/:team/**\*(Aq => sub { \& var team => route_parameters\->get(\*(Aqteam\*(Aq); \& pass; \& }; \& \& prefix \*(Aq/team/:team\*(Aq; \& \& get \*(Aq/player/*\*(Aq => sub { \& my ($player) = splat; \& \& # etc... \& }; \& \& get \*(Aq/score\*(Aq => sub { \& return score_for( vars\->{\*(Aqteam\*(Aq} ); \& }; .Ve .PP \fIRegular Expression Matching\fR .IX Subsection "Regular Expression Matching" .PP A route can be defined with a Perl regular expression. .PP In order to tell Dancer2 to consider the route as a real regexp, the route must be defined explicitly with \f(CW\*(C`qr{}\*(C'\fR, like the following: .PP .Vb 4 \& get qr{/hello/([\ew]+)} => sub { \& my ($name) = splat; \& return "Hello $name"; \& }; .Ve .PP For Perl 5.10+, a route regex may use named capture groups. The \f(CW\*(C`captures\*(C'\fR keyword will return a reference to a copy of \f(CW\*(C`%+\*(C'\fR. .PP \fIConditional Matching\fR .IX Subsection "Conditional Matching" .PP Routes may include some matching conditions (on content_type, agent, user_agent, content_length and path_info): .PP .Vb 3 \& get \*(Aq/foo\*(Aq, {agent => \*(AqSongbird (\ed\e.\ed)[\ed\e/]*?\*(Aq} => sub { \& \*(Aqfoo method for songbird\*(Aq \& } \& \& get \*(Aq/foo\*(Aq => sub { \& \*(Aqall browsers except songbird\*(Aq \& } .Ve .SS "Prefix" .IX Subsection "Prefix" A prefix can be defined for each route handler, like this: .PP .Vb 1 \& prefix \*(Aq/home\*(Aq; .Ve .PP From here, any route handler is defined to /home/* .PP .Vb 1 \& get \*(Aq/page1\*(Aq => sub {}; # will match \*(Aq/home/page1\*(Aq .Ve .PP You can unset the prefix value .PP .Vb 2 \& prefix \*(Aq/\*(Aq; # or: prefix undef; \& get \*(Aq/page1\*(Aq => sub {}; # will match /page1 .Ve .PP Alternatively, to prevent you from ever forgetting to undef the prefix, you can use lexical prefix like this: .PP .Vb 3 \& prefix \*(Aq/home\*(Aq => sub { \& get \*(Aq/page1\*(Aq => sub {}; # will match \*(Aq/home/page1\*(Aq \& }; ## prefix reset to previous value on exit \& \& get \*(Aq/page1\*(Aq => sub {}; # will match /page1 .Ve .SS "Delayed responses (Async/Streaming)" .IX Subsection "Delayed responses (Async/Streaming)" Dancer2 can provide delayed (otherwise known as \fIasynchronous\fR) responses using the \f(CW\*(C`delayed\*(C'\fR keyword. These responses are streamed, although you can set the content all at once, if you prefer. .PP .Vb 3 \& get \*(Aq/status\*(Aq => sub { \& delayed { \& response_header \*(AqX\-Foo\*(Aq => \*(AqBar\*(Aq; \& \& # flush headers (in case of streaming) \& flush; \& \& # send content to the user \& content \*(AqHello, world!\*(Aq; \& \& # you can write more content \& # all streaming \& content \*(AqHello, again!\*(Aq; \& \& # when done, close the connection \& done; \& \& # do whatever you want else, asynchronously \& # the user socket closed by now \& ... \& }; \& }; .Ve .PP If you are streaming (calling \f(CW\*(C`content\*(C'\fR several times), you must call \&\f(CW\*(C`flush\*(C'\fR first. If you're sending only once, you don't need to call \f(CW\*(C`flush\*(C'\fR. .PP Here is an example of using delayed responses with AnyEvent: .PP .Vb 2 \& use Dancer2; \& use AnyEvent; \& \& my %timers; \& my $count = 5; \& get \*(Aq/drums\*(Aq => sub { \& delayed { \& print "Stretching...\en"; \& flush; # necessary, since we\*(Aqre streaming \& \& $timers{\*(AqSnare\*(Aq} = AE::timer 1, 1, delayed { \& $timers{\*(AqHiHat\*(Aq} ||= AE::timer 0, 0.5, delayed { \& content "Tss...\en"; \& }; \& \& content "Bap!\en"; \& \& if ( $count\-\- == 0 ) { \& %timers = (); \& content "Tugu tugu tugu dum!\en"; \& done; \& \& print "\en\en"; \& $timers{\*(AqApplause\*(Aq} = AE::timer 3, 0, sub { \& # the DSL will not available here \& # because we didn\*(Aqt call the "delayed" keyword \& print "\en"; \& }; \& } \& }; \& }; \& }; .Ve .PP If an error happens during a write operation, a warning will be issued to the logger. .PP You can handle the error yourself by providing an \f(CW\*(C`on_error\*(C'\fR handler: .PP .Vb 4 \& get \*(Aq/\*(Aq => sub { \& delayed { \& flush; \& content "works"; \& \& # ... user disconnected here ... \& \& content "fails"; \& \& # ... error triggered ... \& \& done; # doesn\*(Aqt even get run \& } on_error => sub { \& # delayed{} not needed, DSL already available \& my ($error) = @_; \& # do something with $error \& }; \& }; .Ve .PP Here is an example that asynchronously streams the contents of a \s-1CSV\s0 file: .PP .Vb 10 \& use Dancer2; \& use Text::CSV_XS qw< csv >; \& use Path::Tiny qw< path >; \& use JSON::MaybeXS qw< encode_json >; \& # Create CSV parser \& my $csv = Text::CSV_XS\->new({ \& binary => 1, \& auto_diag => 1, \& }); \& get \*(Aq/\*(Aq => sub { \& # delayed response: \& delayed { \& # streaming content \& flush; \& # Read each row and stream it in JSON \& my $fh = path(\*(Aqfilename.csv\*(Aq)\->openr_utf8; \& while ( my $row = $csv\->getline($fh) ) { \& content encode_json $row; \& } \& # close user connection \& done; \& } on_error => sub { \& my ($error) = @_; \& warning \*(AqFailed to stream to user: \*(Aq . request\->remote_address; \& }; \& }; .Ve .PP \&\fB\s-1NOTE:\s0\fR If you just want to send a file's contents asynchronously, use \f(CW\*(C`send_file($filename)\*(C'\fR instead of \f(CW\*(C`delayed\*(C'\fR, as it will automatically take advantage of any asynchronous capability. .SS "Action Skipping" .IX Subsection "Action Skipping" An action can choose not to serve the current request and ask Dancer2 to process the request with the next matching route. .PP This is done with the \fBpass\fR keyword, like in the following example .PP .Vb 4 \& get \*(Aq/say/:word\*(Aq => sub { \& pass if route_parameters\->get(\*(Aqword\*(Aq) =~ /^\ed+$/; \& "I say a word: " . route_parameters\->get(\*(Aqword\*(Aq); \& }; \& \& get \*(Aq/say/:number\*(Aq => sub { \& "I say a number: " . route_parameters\->get(\*(Aqnumber\*(Aq); \& }; .Ve .SH "HOOKS" .IX Header "HOOKS" Hooks are code references (or anonymous subroutines) that are triggered at specific moments during the resolution of a request. They are set up using the hook keyword. .PP Many of them are provided by Dancer2's core, but plugins and engines can also define their own. .IP "\(bu" 4 \&\f(CW\*(C`before\*(C'\fR hooks .Sp \&\f(CW\*(C`before\*(C'\fR hooks are evaluated before each request within the context of the request and receives as argument the app (a Dancer2::Core::App object). .Sp It's possible to define variables which will be accessible in the action blocks with the var keyword. .Sp .Vb 3 \& hook before => sub { \& var note => \*(AqHi there\*(Aq; \& }; \& \& get \*(Aq/foo/*\*(Aq => sub { \& my ($match) = splat; # \*(Aqoversee\*(Aq; \& vars\->{note}; # \*(AqHi there\*(Aq \& }; .Ve .Sp For another example, this can be used along with session support to easily give non-logged-in users a login page: .Sp .Vb 6 \& hook before => sub { \& if (!session(\*(Aquser\*(Aq) && request\->path !~ m{^/login}) { \& # Pass the original path requested along to the handler: \& forward \*(Aq/login\*(Aq, { requested_path => request\->path }; \& } \& }; .Ve .Sp The request keyword returns the current Dancer2::Core::Request object representing the incoming request. .IP "\(bu" 4 \&\f(CW\*(C`after\*(C'\fR hooks .Sp \&\f(CW\*(C`after\*(C'\fR 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. .Sp This hook runs after a request has been processed, but before the response is sent. .Sp It receives a Dancer2::Core::Response object, which it can modify if it needs to make changes to the response which is about to be sent. .Sp The hook can use other keywords in order to do whatever it wants. .Sp .Vb 5 \& hook after => sub { \& response\->content( \& q{The "after" hook can alter the response\*(Aqs content here!} \& ); \& }; .Ve .SS "Templates" .IX Subsection "Templates" .IP "\(bu" 4 \&\f(CW\*(C`before_template_render\*(C'\fR .Sp \&\f(CW\*(C`before_template_render\*(C'\fR hooks are called whenever a template is going to be processed, they are passed the tokens hash which they can alter. .Sp .Vb 4 \& hook before_template_render => sub { \& my $tokens = shift; \& $tokens\->{foo} = \*(Aqbar\*(Aq; \& }; .Ve .Sp 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. .IP "\(bu" 4 \&\f(CW\*(C`after_template_render\*(C'\fR .Sp \&\f(CW\*(C`after_template_render\*(C'\fR hooks are called after the view has been rendered. They receive as their first argument the reference to the content that has been produced. This can be used to post-process the content rendered by the template engine. .Sp .Vb 3 \& hook after_template_render => sub { \& my $ref_content = shift; \& my $content = ${$ref_content}; \& \& # do something with $content \& ${$ref_content} = $content; \& }; .Ve .IP "\(bu" 4 \&\f(CW\*(C`before_layout_render\*(C'\fR .Sp \&\f(CW\*(C`before_layout_render\*(C'\fR hooks are called whenever the layout is going to be applied to the current content. The arguments received by the hook are the current tokens hashref and a reference to the current content. .Sp .Vb 5 \& hook before_layout_render => sub { \& my ($tokens, $ref_content) = @_; \& $tokens\->{new_stuff} = 42; \& $ref_content = \e"new content"; \& }; .Ve .IP "\(bu" 4 \&\f(CW\*(C`after_layout_render\*(C'\fR .Sp \&\f(CW\*(C`after_layout_render\*(C'\fR hooks are called once the complete content of the view has been produced, after the layout has been applied to the content. The argument received by the hook is a reference to the complete content string. .Sp .Vb 5 \& hook after_layout_render => sub { \& my $ref_content = shift; \& # do something with ${ $ref_content }, which reflects directly \& # in the caller \& }; .Ve .SS "Error Handling" .IX Subsection "Error Handling" Refer to Error Hooks for details about the following hooks: .IP "\(bu" 4 \&\f(CW\*(C`init_error\*(C'\fR .IP "\(bu" 4 \&\f(CW\*(C`before_error\*(C'\fR .IP "\(bu" 4 \&\f(CW\*(C`after_error\*(C'\fR .IP "\(bu" 4 \&\f(CW\*(C`on_route_exception\*(C'\fR .SS "File Rendering" .IX Subsection "File Rendering" Refer to File Handler for details on the following hooks: .IP "\(bu" 4 \&\f(CW\*(C`before_file_render\*(C'\fR .IP "\(bu" 4 \&\f(CW\*(C`after_file_render\*(C'\fR .SS "Serializers" .IX Subsection "Serializers" .IP "\(bu" 4 \&\f(CW\*(C`before_serializer\*(C'\fR is called before serializing the content, and receives the content to serialize as an argument. .Sp .Vb 4 \& hook before_serializer => sub { \& my $content = shift; \& ... \& }; .Ve .IP "\(bu" 4 \&\f(CW\*(C`after_serializer\*(C'\fR is called after the payload has been serialized, and receives the serialized content as an argument. .Sp .Vb 4 \& hook after_serializer => sub { \& my $serialized_content = shift; \& ... \& }; .Ve .SH "HANDLERS" .IX Header "HANDLERS" .SS "File Handler" .IX Subsection "File Handler" Whenever a content is produced out of the parsing of a static file, the Dancer2::Handler::File component is used. This component provides two hooks, \f(CW\*(C`before_file_render\*(C'\fR and \f(CW\*(C`after_file_render\*(C'\fR. .PP \&\f(CW\*(C`before_file_render\*(C'\fR hooks are called just before starting to parse the file, the hook receives as its first argument the file path that is going to be processed. .PP .Vb 3 \& hook before_file_render => sub { \& my $path = shift; \& }; .Ve .PP \&\f(CW\*(C`after_file_render\*(C'\fR hooks are called after the file has been parsed and the response content produced. It receives the response object (Dancer2::Core::Response) produced. .PP .Vb 3 \& hook after_file_render => sub { \& my $response = shift; \& }; .Ve .SS "Auto page" .IX Subsection "Auto page" Whenever a page that matches an existing template needs to be served, the Dancer2::Handler::AutoPage component is used. .SS "Writing your own" .IX Subsection "Writing your own" A route handler is a class that consumes the Dancer2::Core::Role::Handler role. The class must implement a set of methods: \f(CW\*(C`methods\*(C'\fR, \f(CW\*(C`regexp\*(C'\fR and \&\f(CW\*(C`code\*(C'\fR which will be used to declare the route. .PP Let's look at Dancer2::Handler::AutoPage for example. .PP First, the matching methods are \f(CW\*(C`get\*(C'\fR and \f(CW\*(C`head\*(C'\fR: .PP .Vb 1 \& sub methods { qw(head get) } .Ve .PP Then, the \f(CW\*(C`regexp\*(C'\fR or the \fIpath\fR we want to match: .PP .Vb 1 \& sub regexp { \*(Aq/:page\*(Aq } .Ve .PP Anything will be matched by this route, since we want to check if there's a view named with the value of the \f(CW\*(C`page\*(C'\fR token. If not, the route needs to \f(CW\*(C`pass\*(C'\fR, letting the dispatching flow to proceed further. .PP .Vb 4 \& sub code { \& sub { \& my $app = shift; \& my $prefix = shift; \& \& my $template = $app\->template_engine; \& if ( !defined $template ) { \& $app\->response\->has_passed(1); \& return; \& } \& \& my $page = $app\->request\->path; \& my $layout_dir = $template\->layout_dir; \& if ( $page =~ m{^/\eQ$layout_dir\eE/} ) { \& $app\->response\->has_passed(1); \& return; \& } \& \& # remove leading \*(Aq/\*(Aq, ensuring paths relative to the view \& $page =~ s{^/}{}; \& my $view_path = $template\->view_pathname($page); \& \& if ( ! $template\->pathname_exists( $view_path ) ) { \& $app\->response\->has_passed(1); \& return; \& } \& \& my $ct = $template\->process( $page ); \& return ( $app\->request\->method eq \*(AqGET\*(Aq ) ? $ct : \*(Aq\*(Aq; \& }; \& } .Ve .PP The \f(CW\*(C`code\*(C'\fR method passed the Dancer2::Core::App object which provides access to anything needed to process the request. .PP A \f(CW\*(C`register\*(C'\fR is then implemented to add the route to the registry and if the \f(CW\*(C`auto_page setting\*(C'\fR is off, it does nothing. .PP .Vb 2 \& sub register { \& my ($self, $app) = @_; \& \& return unless $app\->config\->{auto_page}; \& \& $app\->add_route( \& method => $_, \& regexp => $self\->regexp, \& code => $self\->code, \& ) for $self\->methods; \& } .Ve .PP The config parser looks for a \f(CW\*(C`route_handlers\*(C'\fR section and any handler defined there is loaded. Thus, any random handler can be added to your app. For example, the default config file for any Dancer2 application is as follows: .PP .Vb 4 \& route_handlers: \& File: \& public_dir: /path/to/public \& AutoPage: 1 .Ve .SH "ERRORS" .IX Header "ERRORS" .SS "Error Pages" .IX Subsection "Error Pages" When an \s-1HTTP\s0 error occurs (i.e. the action responds with a status code other than 200), this is how Dancer2 determines what page to display. .IP "\(bu" 4 Looks in the \f(CW\*(C`views/\*(C'\fR directory for a corresponding template file matching the error code (e.g. \f(CW\*(C`500.tt\*(C'\fR or \f(CW\*(C`404.tt\*(C'\fR). If such a file exists, it's used to report the error. .IP "\(bu" 4 Next, looks in the \f(CW\*(C`public/\*(C'\fR directory for a corresponding \s-1HTML\s0 file matching the error code (e.g. \f(CW\*(C`500.html\*(C'\fR or \f(CW\*(C`404.html\*(C'\fR). If such a file exists, it's used to report the error. (Note, however, that if \fBshow_errors\fR is set to true, in the case of a 500 error the static \s-1HTML\s0 page will not be shown, but will be replaced with a default error page containing more informative diagnostics. For more information see Dancer2::Config.) .IP "\(bu" 4 As default, render a generic error page on the fly. .SS "Execution Errors" .IX Subsection "Execution Errors" When an error occurs during the route execution, Dancer2 will render an error page with the \s-1HTTP\s0 status code 500. .PP 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 controlled with the \fBshow_errors\fR setting (see above). .SS "Error Hooks" .IX Subsection "Error Hooks" When an error is caught by Dancer2's core, an exception object is built (of the class Dancer2::Core::Error). This class provides a hook to let the user alter the error workflow if needed. .PP \&\f(CW\*(C`init_error\*(C'\fR hooks are called whenever an error object is built, the object is passed to the hook. .PP .Vb 4 \& hook init_error => sub { \& my $error = shift; \& # do something with $error \& }; .Ve .PP \&\fIThis hook was named \f(BIbefore_error_init\fI in Dancer, both names currently are synonyms for backward-compatibility.\fR .PP \&\f(CW\*(C`before_error\*(C'\fR hooks are called whenever an error is going to be thrown, it receives the error object as its sole argument. .PP .Vb 4 \& hook before_error => sub { \& my $error = shift; \& # do something with $error \& }; .Ve .PP \&\fIThis hook was named \f(BIbefore_error_render\fI in Dancer, both names currently are synonyms for backward-compatibility.\fR .PP \&\f(CW\*(C`after_error\*(C'\fR hooks are called whenever an error object has been thrown, it receives a Dancer2::Core::Response object as its sole argument. .PP .Vb 3 \& hook after_error => sub { \& my $response = shift; \& }; .Ve .PP \&\fIThis hook was named \f(BIafter_error_render\fI in Dancer, both names currently are synonyms for backward-compatibility.\fR .PP \&\f(CW\*(C`on_route_exception\*(C'\fR is called when an exception has been caught, at the route level, just before rethrowing it higher. This hook receives a Dancer2::Core::App and the error as arguments. .PP .Vb 3 \& hook on_route_exception => sub { \& my ($app, $error) = @_; \& }; .Ve .SH "SESSIONS" .IX Header "SESSIONS" .SS "Handling sessions" .IX Subsection "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. .PP By default Dancer 2 has Simple sessions enabled. It implements a 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. .PP If you'd like to use a different session engine you must declare it in the configuration file. .PP For example to use \s-1YAML\s0 file base sessions you need to add the following to your \fIconfig.yml\fR: .PP .Vb 1 \& session: YAML .Ve .PP Or, to enable session support from within your code, .PP .Vb 1 \& set session => \*(AqYAML\*(Aq; .Ve .PP (However, controlling settings is best done from your config file.) .PP The Dancer2::Session::YAML backend implements a file-based \s-1YAML\s0 session storage to help with debugging, but shouldn't be used on production systems. .PP There are other session backends, such as Dancer2::Session::Memcached, which are recommended for production use. .PP You can then use the session keyword to manipulate the session: .PP \fIStoring data in the session\fR .IX Subsection "Storing data in the session" .PP Storing data in the session is as easy as: .PP .Vb 1 \& session varname => \*(Aqvalue\*(Aq; .Ve .PP \fIRetrieving data from the session\fR .IX Subsection "Retrieving data from the session" .PP Retrieving data from the session is as easy as: .PP .Vb 1 \& session(\*(Aqvarname\*(Aq) .Ve .PP Or, alternatively, .PP .Vb 1 \& session\->read("varname") .Ve .PP \fIControlling where sessions are stored\fR .IX Subsection "Controlling where sessions are stored" .PP For disc-based session backends like Dancer2::Session::YAML, session files are written to the session dir specified by the \f(CW\*(C`session_dir\*(C'\fR setting, which defaults to \f(CW\*(C`./sessions\*(C'\fR if not specifically set. .PP If you need to control where session files are created, you can do so quickly and easily within your config file, for example: .PP .Vb 5 \& session: YAML \& engines: \& session: \& YAML: \& session_dir: /tmp/dancer\-sessions .Ve .PP If the directory you specify does not exist, Dancer2 will attempt to create it for you. .PP \fIChanging session \s-1ID\s0\fR .IX Subsection "Changing session ID" .PP If you wish to change the session \s-1ID\s0 (for example on privilege level change): .PP .Vb 1 \& my $new_session_id = app\->change_session_id .Ve .PP \fIDestroying a session\fR .IX Subsection "Destroying a session" .PP When you're done with your session, you can destroy it: .PP .Vb 1 \& app\->destroy_session .Ve .SS "Sessions and logging in" .IX Subsection "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. .PP This can easily be handled using a before hook to check their session: .PP .Vb 2 \& use Dancer2; \& set session => "Simple"; \& \& hook before => sub { \& if (!session(\*(Aquser\*(Aq) && request\->path !~ m{^/login}) { \& forward \*(Aq/login\*(Aq, { requested_path => request\->path }; \& } \& }; \& \& get \*(Aq/\*(Aq => sub { return "Home Page"; }; \& \& get \*(Aq/secret\*(Aq => sub { return "Top Secret Stuff here"; }; \& \& get \*(Aq/login\*(Aq => sub { \& # Display a login page; the original URL they requested is available as \& # query_parameters\->get(\*(Aqrequested_path\*(Aq), so could be put in a hidden field in the form \& template \*(Aqlogin\*(Aq, { path => query_parameters\->get(\*(Aqrequested_path\*(Aq) }; \& }; \& \& post \*(Aq/login\*(Aq => sub { \& # Validate the username and password they supplied \& if (body_parameters\->get(\*(Aquser\*(Aq) eq \*(Aqbob\*(Aq && body_parameters\->get(\*(Aqpass\*(Aq) eq \*(Aqletmein\*(Aq) { \& session user => body_parameters\->get(\*(Aquser\*(Aq); \& redirect body_parameters\->get(\*(Aqpath\*(Aq) || \*(Aq/\*(Aq; \& } else { \& redirect \*(Aq/login?failed=1\*(Aq; \& } \& }; \& \& dance(); .Ve .PP Here is what the corresponding \f(CW\*(C`login.tt\*(C'\fR file should look like. You should place it in a directory called \f(CW\*(C`views/\*(C'\fR: .PP .Vb 8 \& \& \& Session and logging in \& \& \&
\& User Name : \& Password: \& \& \& \*(Aq/> \& \& \&
\& \& .Ve .PP 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 \s-1PAM\s0 etc. Authen::Simple is probably a good starting point here! .PP A simple working example of handling authentication against a database table yourself (using Dancer2::Plugin::Database which provides the \f(CW\*(C`database\*(C'\fR keyword, and Crypt::SaltedHash to handle salted hashed passwords (well, you wouldn't store your users passwords in the clear, would you?)) follows: .PP .Vb 3 \& post \*(Aq/login\*(Aq => sub { \& my $user_value = body_parameters\->get(\*(Aquser\*(Aq); \& my $pass_value = body_parameters\->get(\*(Aqpass\*(Aq); \& \& my $user = database\->quick_select(\*(Aqusers\*(Aq, \& { username => $user_value } \& ); \& if (!$user) { \& warning "Failed login for unrecognised user $user_value"; \& redirect \*(Aq/login?failed=1\*(Aq; \& } else { \& if (Crypt::SaltedHash\->validate($user\->{password}, $pass_value)) \& { \& debug "Password correct"; \& # Logged in successfully \& session user => $user; \& redirect body_parameters\->get(\*(Aqpath\*(Aq) || \*(Aq/\*(Aq; \& } else { \& debug("Login failed \- password incorrect for " . $user_value); \& redirect \*(Aq/login?failed=1\*(Aq; \& } \& } \& }; .Ve .PP \fIRetrieve complete hash stored in session\fR .IX Subsection "Retrieve complete hash stored in session" .PP Get complete hash stored in session: .PP .Vb 1 \& my $hash = session; .Ve .SS "Writing a session engine" .IX Subsection "Writing a session engine" In Dancer 2, a session backend consumes the role Dancer2::Core::Role::SessionFactory. .PP The following example using the Redis session demonstrates how session engines are written in Dancer 2. .PP First thing to do is to create the class for the session engine, we'll name it \f(CW\*(C`Dancer2::Session::Redis\*(C'\fR: .PP .Vb 3 \& package Dancer2::Session::Redis; \& use Moo; \& with \*(AqDancer2::Core::Role::SessionFactory\*(Aq; .Ve .PP we want our backend to have a handle over a Redis connection. To do that, we'll create an attribute \f(CW\*(C`redis\*(C'\fR .PP .Vb 3 \& use JSON; \& use Redis; \& use Dancer2::Core::Types; # brings helper for types \& \& has redis => ( \& is => \*(Aqrw\*(Aq, \& isa => InstanceOf[\*(AqRedis\*(Aq], \& lazy => 1, \& builder => \*(Aq_build_redis\*(Aq, \& ); .Ve .PP The lazy attribute says to Moo that this attribute will be built (initialized) only when called the first time. It means that the connection to Redis won't be opened until necessary. .PP .Vb 8 \& sub _build_redis { \& my ($self) = @_; \& Redis\->new( \& server => $self\->server, \& password => $self\->password, \& encoding => undef, \& ); \& } .Ve .PP Two more attributes, \f(CW\*(C`server\*(C'\fR and \f(CW\*(C`password\*(C'\fR need to be created. We do this by defining them in the config file. Dancer2 passes anything defined in the config to the engine creation. .PP .Vb 7 \& # config.yml \& ... \& engines: \& session: \& Redis: \& server: foo.mydomain.com \& password: S3Cr3t .Ve .PP The server and password entries are now passed to the constructor of the Redis session engine and can be accessed from there. .PP .Vb 2 \& has server => (is => \*(Aqro\*(Aq, required => 1); \& has password => (is => \*(Aqro\*(Aq); .Ve .PP Next, we define the subroutine \f(CW\*(C`_retrieve\*(C'\fR which will return a session object for a session \s-1ID\s0 it has passed. Since in this case, sessions are going to be stored in Redis, the session \s-1ID\s0 will be the key, the session the value. So retrieving is as easy as doing a get and decoding the \s-1JSON\s0 string returned: .PP .Vb 6 \& sub _retrieve { \& my ($self, $session_id) = @_; \& my $json = $self\->redis\->get($session_id); \& my $hash = from_json( $json ); \& return bless $hash, \*(AqDancer2::Core::Session\*(Aq; \& } .Ve .PP The \f(CW\*(C`_flush\*(C'\fR method is called by Dancer when the session needs to be stored in the backend. That is actually a write to Redis. The method receives a \f(CW\*(C`Dancer2::Core::Session\*(C'\fR object and is supposed to store it. .PP .Vb 5 \& sub _flush { \& my ($self, $session) = @_; \& my $json = encode_json( { %{ $session } } ); \& $self\->redis\->set($session\->id, $json); \& } .Ve .PP For the \f(CW\*(C`_destroy\*(C'\fR method which is supposed to remove a session from the backend, deleting the key from Redis is enough. .PP .Vb 4 \& sub _destroy { \& my ($self, $session_id) = @_; \& $self\->redis\->del($session_id); \& } .Ve .PP The \f(CW\*(C`_sessions\*(C'\fR method which is supposed to list all the session IDs currently stored in the backend is done by listing all the keys that Redis has. .PP .Vb 5 \& sub _sessions { \& my ($self) = @_; \& my @keys = $self\->redis\->keys(\*(Aq*\*(Aq); \& return \e@keys; \& } .Ve .PP The session engine is now ready. .PP \fIThe Session keyword\fR .IX Subsection "The Session keyword" .PP Dancer2 maintains two session layers. .PP The first layer, Dancer2::Core::Session provides a session object which represents the current session. You can read from it as many times as you want, and write to it as many times as you want. .PP The second layer is the session engine (Dancer2::Session::Simple is one example), which is used in order to implement the reading and writing from the actual storage. This is read only once, when a request comes in (using a cookie whose value is \f(CW\*(C`dancer.session\*(C'\fR by default). At the end of a request, all the data you've written will be flushed to the engine itself, which will do the actual write to the storage (whether it's in a hash in memory, in Memcache, or in a database). .SH "TEMPLATES" .IX Header "TEMPLATES" 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. .PP Your route handlers can use the template keyword to render templates. .SS "Views" .IX Subsection "Views" In Dancer2, a file which holds a template is called a \fIview\fR. Views are located in the \f(CW\*(C`appdir/views\*(C'\fR directory. .PP You can change this location by changing the setting 'views'. For instance if your templates are located in the 'templates' directory, do the following: .PP .Vb 1 \& set views => path( app\->location , \*(Aqtemplates\*(Aq ); .Ve .PP By default, the internal template engine Dancer2::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 Dancer2::Template::TemplateToolkit and you'll also have to install the Template module. .PP In order to render a view, just call the template keyword at the end of the action by giving the view name and the \s-1HASHREF\s0 of tokens to interpolate in the view (note that for convenience, the request, session, params and vars are automatically accessible in the view, named \f(CW\*(C`request\*(C'\fR, \f(CW\*(C`session\*(C'\fR, \f(CW\*(C`params\*(C'\fR, and \f(CW\*(C`vars\*(C'\fR) \- for example: .PP .Vb 1 \& hook before => sub { var time => scalar(localtime) }; \& \& get \*(Aq/hello/:name\*(Aq => sub { \& my $name = route_parameters\->get(\*(Aqname\*(Aq); \& template \*(Aqhello.tt\*(Aq, { name => $name }; \& }; .Ve .PP The template \f(CW\*(C`hello.tt\*(C'\fR could contain, for example: .PP .Vb 6 \&

Hi there, [% name %]!

\&

You\*(Aqre using [% request.user_agent %]

\& [% IF session.username %] \&

You\*(Aqre logged in as [% session.username %]

\& [% END %] \& It\*(Aqs currently [% vars.time %] .Ve .PP For a full list of the tokens automatically added to your template (like \&\f(CW\*(C`session\*(C'\fR, \f(CW\*(C`request\*(C'\fR, and \f(CW\*(C`vars\*(C'\fR, refer to Dancer2::Core::Role::Template). .PP By default, views use a \fI.tt\fR extension. This can be overridden by setting the \f(CW\*(C`extension\*(C'\fR attribute in the template engine configuration: .PP .Vb 7 \& set engines => { \& template => { \& template_toolkit => { \& extension => \*(Aqfoo\*(Aq, \& }, \& }, \& }; .Ve .SS "Layouts" .IX Subsection "Layouts" A layout is a special view, located in the \fIlayouts\fR directory (inside the views directory) which must have a token named \f(CW\*(C`content\*(C'\fR. 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 and helps avoid lots of needless duplication of \s-1HTML. :\s0) .PP For example, the layout \fIviews/layouts/main.tt\fR: .PP .Vb 6 \& \& ... \& \& \& \&
\& [% content %] \&
\& \& \& .Ve .PP You can tell your app which layout to use with \f(CW\*(C`layout: name\*(C'\fR in the config file, or within your code: .PP .Vb 1 \& set layout => \*(Aqmain\*(Aq; .Ve .PP 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: .PP .Vb 1 \& template \*(Aqindex.tt\*(Aq, {}, { layout => undef }; .Ve .PP If your application is not mounted under root (\f(CW\*(C`/\*(C'\fR), you can use a \&\f(CW\*(C`before_template_render\*(C'\fR hook instead of hardcoding the path into your application for your \s-1CSS,\s0 images and JavaScript: .PP .Vb 4 \& hook before_template_render => sub { \& my $tokens = shift; \& $tokens\->{uri_base} = request\->base\->path; \& }; .Ve .PP Then in your layout, modify your \s-1CSS\s0 inclusion as follows: .PP .Vb 1 \& .Ve .PP From now on you can mount your application wherever you want, without any further modification of the \s-1CSS\s0 inclusion. .SS "Encoding" .IX Subsection "Encoding" If you use 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 \s-1UTF\-8.\s0 So, if you are using template toolkit, your config file will look like this: .PP .Vb 5 \& charset: UTF\-8 \& engines: \& template: \& template_toolkit: \& ENCODING: utf8 .Ve .SS "Default Template Variables" .IX Subsection "Default Template Variables" Every template knows about the following variables, which are provided by Dancer2::Core::Role::Template. Some are similar to the keywords you can use in the Perl part of your Dancer2 application. .IP "\(bu" 4 \&\fBperl_version\fR .Sp Current version of perl, effectively \&\f(CW$^V\fR . .IP "\(bu" 4 \&\fBdancer_version\fR .Sp Current version of Dancer2, effectively \f(CW\*(C`Dancer2\->VERSION\*(C'\fR. .IP "\(bu" 4 \&\fBsettings\fR .Sp A hash of the application configuration. This is like the config keyword. .IP "\(bu" 4 \&\fBrequest\fR .Sp The current request object. This is like the request keyword. .IP "\(bu" 4 \&\fBparams\fR .Sp A hash reference of all the parameters. .Sp Currently the equivalent of \f(CW\*(C`$request\->params\*(C'\fR, and like the params keyword. .IP "\(bu" 4 \&\fBvars\fR .Sp The list of request variables, which is what you would get if you called the vars keyword. .IP "\(bu" 4 \&\fBsession\fR .Sp The current session data, if a session exists. This is like the session keyword. .SH "STATIC FILES" .IX Header "STATIC FILES" .SS "Static Directory" .IX Subsection "Static Directory" Static files are served from the \fI./public\fR directory. You can specify a different location by setting the \f(CW\*(C`public_dir\*(C'\fR option: .PP .Vb 1 \& set public_dir => path( app\->location , \*(Aqstatic\*(Aq ); .Ve .PP When you modify default public_dir you have to set \f(CW\*(C`static_handler\*(C'\fR option. .PP .Vb 1 \& set static_handler => true; .Ve .PP Note that the public directory name is not included in the \s-1URL. A\s0 file \&\fI./public/css/style.css\fR is made available as . .SS "Static File from a Route Handler" .IX Subsection "Static File from a Route Handler" It's possible for a route handler to send a static file, as follows: .PP .Vb 2 \& get \*(Aq/download/*\*(Aq => sub { \& my ($file) = splat; \& \& send_file $file; \& }; .Ve .PP Or even if you want your index page to be a plain old \fIindex.html\fR file, just do: .PP .Vb 3 \& get \*(Aq/\*(Aq => sub { \& send_file \*(Aq/index.html\*(Aq \& }; .Ve .SH "FILE UPLOADS" .IX Header "FILE UPLOADS" Files are uploaded in Dancer2 using the class Dancer2::Core::Request::Upload. The objects are accessible within the route handlers using the \f(CW\*(C`upload\*(C'\fR keyword: .PP .Vb 4 \& post \*(Aq/upload\*(Aq => sub { \& my $upload = upload(\*(Aqfile_input_name\*(Aq); # upload object \& $upload\->copy_to(\*(AqUploads/\*(Aq); \& }; .Ve .SH "CONFIGURATION" .IX Header "CONFIGURATION" .SS "Configuration and environments" .IX Subsection "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 \f(CW\*(C`dance()\*(C'\fR method. .PP Other ways are possible: for example, you can define all your settings in the file \&\f(CW\*(C`appdir/config.yml\*(C'\fR. For this, you must have installed the \s-1YAML\s0 module, and of course, write the config file in \s-1YAML.\s0 .PP 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. .PP A better solution is to have one \fIconfig.yml\fR file with default global settings, like the following: .PP .Vb 3 \& # appdir/config.yml \& logger: \*(Aqfile\*(Aq \& layout: \*(Aqmain\*(Aq .Ve .PP And then write as many environment files as you like in \&\f(CW\*(C`appdir/environments\*(C'\fR. That way, the appropriate environment config file will be loaded according to the running environment (if none is specified, it will be 'development'). .PP You can change the running environment when starting your app using the \&\f(CW\*(C`plackup\*(C'\fR command's \f(CW\*(C`\-\-env\*(C'\fR or \f(CW\*(C`\-\-E\*(C'\fR switch: .PP .Vb 1 \& plackup \-E production bin/app.psgi .Ve .PP Altenatively, you can set the \&\f(CW\*(C`DANCER_ENVIRONMENT\*(C'\fR environment variable in the shell or in your web server's configuration file. .PP Typically, you'll want to set the following values in a development config file: .PP .Vb 4 \& # appdir/environments/development.yml \& log: \*(Aqdebug\*(Aq \& startup_info: 1 \& show_errors: 1 .Ve .PP And in a production one: .PP .Vb 4 \& # appdir/environments/production.yml \& log: \*(Aqwarning\*(Aq \& startup_info: 0 \& show_errors: 0 .Ve .PP Please note that you are not limited to writing configuration files in \s-1YAML.\s0 Dancer2 supports any file format that is supported by Config::Any, such as \s-1JSON, XML, INI\s0 files, and Apache-style config files. See the Dancer2 configuration guide for more information. .SS "Accessing configuration information" .IX Subsection "Accessing configuration information" A Dancer2 application can use the \f(CW\*(C`config\*(C'\fR keyword to easily access the settings within its config file, for instance: .PP .Vb 3 \& get \*(Aq/appname\*(Aq => sub { \& return "This is " . config\->{appname}; \& }; .Ve .PP 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. :) .SS "Settings" .IX Subsection "Settings" It's possible to change almost every parameter of the application via the settings mechanism. .PP A setting is a key/value pair assigned by the keyword \fBset\fR: .PP .Vb 1 \& set setting_name => \*(Aqsetting_value\*(Aq; .Ve .PP More usefully, settings can be defined in a configuration file. Environment-specific settings can also be defined in environment-specific files (for instance, you do not want to show error stacktraces in production, and might want extra logging in development). .SS "Serializers" .IX Subsection "Serializers" When writing a webservice, data serialization/deserialization is a common issue to deal with. Dancer2 can automatically handle that for you, via a serializer. .PP When setting up a serializer, a new behaviour is authorized for any route handler you define: any non-scalar response will be rendered as a serialized string, via the current serializer. .PP Here is an example of a route handler that will return a hashref: .PP .Vb 2 \& use Dancer2; \& set serializer => \*(AqJSON\*(Aq; \& \& get \*(Aq/user/:id/\*(Aq => sub { \& { foo => 42, \& number => 100234, \& list => [qw(one two three)], \& } \& }; .Ve .PP Dancer2 will render the response via the current serializer. .PP Hence, with the \s-1JSON\s0 serializer set, the route handler above would result in a content like the following: .PP .Vb 1 \& {"number":100234,"foo":42,"list":["one","two","three"]} .Ve .PP If you send a value which is validated serialized data, but is not in the form a key and value pair (such as a serialized string or a \s-1JSON\s0 array), the data will not be available in \f(CW\*(C`params\*(C'\fR but will be available in \&\f(CW\*(C`request\->data\*(C'\fR. .PP The following serializers are available, be aware they dynamically depend on Perl modules you may not have on your system. .IP "\(bu" 4 \&\fB\s-1JSON\s0\fR .Sp Requires \s-1JSON\s0. .IP "\(bu" 4 \&\fB\s-1YAML\s0\fR .Sp Requires \s-1YAML\s0, .IP "\(bu" 4 \&\fB\s-1XML\s0\fR .Sp Requires XML::Simple. .IP "\(bu" 4 \&\fBMutable\fR .Sp Will try to find the appropriate serializer using the \fBContent-Type\fR and \&\fBAccept-type\fR header of the request. .SS "Importing using Appname" .IX Subsection "Importing using Appname" An app in Dancer2 uses the class name (defined by the \f(CW\*(C`package\*(C'\fR function) to define the App name. Thus separating the App to multiple files, actually means creating multiple applications. This means that any engine defined in an application, because the application is a complete separate scope, will not be available to a different application: .PP .Vb 5 \& package MyApp::User { \& use Dancer2; \& set serializer => \*(AqJSON\*(Aq; \& get \*(Aq/view\*(Aq => sub {...}; \& } \& \& package MyApp::User::Edit { \& use Dancer2; \& get \*(Aq/edit\*(Aq => sub {...}; \& } .Ve .PP These are two different Dancer2 Apps. They have different scopes, contexts, and thus different engines. While \f(CW\*(C`MyApp::User\*(C'\fR has a serializer defined, \&\f(CW\*(C`MyApp::User::Edit\*(C'\fR will not have that configuration. .PP By using the import option \f(CW\*(C`appname\*(C'\fR, we can ask Dancer2 to extend an App without creating a new one: .PP .Vb 5 \& package MyApp::User { \& use Dancer2; \& set serializer => \*(AqJSON\*(Aq; \& get \*(Aq/view\*(Aq => sub {...}; \& } \& \& package MyApp::User::Edit { \& use Dancer2 appname => \*(AqMyApp::User\*(Aq; # extending MyApp::User \& get \*(Aq/edit\*(Aq => sub {...}; \& } .Ve .PP The import option \f(CW\*(C`appname\*(C'\fR allows you to seamlessly extend Dancer2 Apps without creating unnecessary additional applications or repeat any definitions. This allows you to spread your application routes across multiple files and allow ease of mind when developing it, and accommodate multiple developers working on the same codebase. .PP .Vb 3 \& # app.pl \& use MyApp::User; \& use MyApp::User::Edit; \& \& # single application composed of routes provided in multiple files \& MyApp::User\->to_app; .Ve .PP This way only one class needs to be loaded while creating an app: .PP .Vb 3 \& # app.pl: \& use MyApp::User; \& MyApp::User\->to_app; .Ve .SH "LOGGING" .IX Header "LOGGING" .SS "Configuring logging" .IX Subsection "Configuring logging" It's possible to log messages generated by the application and by Dancer2 itself. .PP To start logging, select the logging engine you wish to use with the \&\f(CW\*(C`logger\*(C'\fR setting; Dancer2 includes built-in log engines named \f(CW\*(C`file\*(C'\fR and \&\f(CW\*(C`console\*(C'\fR, which log to a logfile and to the console respectively. .PP To enable logging to a file, add the following to your config file: .PP .Vb 1 \& logger: \*(Aqfile\*(Aq .Ve .PP Then you can choose which kind of messages you want to actually log: .PP .Vb 6 \& log: \*(Aqcore\*(Aq # will log debug, info, warnings, errors, \& # and messages from Dancer2 itself \& log: \*(Aqdebug\*(Aq # will log debug, info, warning and errors \& log: \*(Aqinfo\*(Aq # will log info, warning and errors \& log: \*(Aqwarning\*(Aq # will log warning and errors \& log: \*(Aqerror\*(Aq # will log only errors .Ve .PP If you're using the \f(CW\*(C`file\*(C'\fR logging engine, a directory \f(CW\*(C`appdir/logs\*(C'\fR will be created and will host one logfile per environment. The log message contains the time it was written, the \s-1PID\s0 of the current process, the message and the caller information (file and line). .SS "Logging your own messages" .IX Subsection "Logging your own messages" Just call debug , info , warning or error with your message: .PP .Vb 1 \& debug "This is a debug message from my app."; .Ve .SH "TESTING" .IX Header "TESTING" .SS "Using Plack::Test" .IX Subsection "Using Plack::Test" Plack::Test receives a common web request (using standard HTTP::Request objects), fakes a web server in order to create a proper \s-1PSGI\s0 request, and sends it to the web application. When the web application returns a \s-1PSGI\s0 response (which Dancer applications do), it will then convert it to a common web response (as a standard HTTP::Response object). .PP This allows you to then create requests in your test, create the code reference for your web application, call them, and receive a response object, which can then be tested. .PP \fIBasic Example\fR .IX Subsection "Basic Example" .PP Assuming there is a web application: .PP .Vb 5 \& # MyApp.pm \& package MyApp; \& use Dancer2; \& get \*(Aq/\*(Aq => sub {\*(AqOK\*(Aq}; \& 1; .Ve .PP The following test \fIbase.t\fR is created: .PP .Vb 7 \& # base.t \& use strict; \& use warnings; \& use Test::More tests => 2; \& use Plack::Test; \& use HTTP::Request; \& use MyApp; .Ve .PP Creating a coderef for the application using the \f(CW\*(C`to_app\*(C'\fR keyword: .PP .Vb 1 \& my $app = MyApp\->to_app; .Ve .PP Creating a test object from Plack::Test for the application: .PP .Vb 1 \& my $test = Plack::Test\->create($app); .Ve .PP Creating the first request object and sending it to the test object to receive a response: .PP .Vb 2 \& my $request = HTTP::Request\->new( GET => \*(Aq/\*(Aq ); \& my $response = $test\->request($request); .Ve .PP It can now be tested: .PP .Vb 2 \& ok( $response\->is_success, \*(Aq[GET /] Successful request\*(Aq ); \& is( $response\->content, \*(AqOK\*(Aq, \*(Aq[GET /] Correct content\*(Aq ); .Ve .PP \fIPutting it together\fR .IX Subsection "Putting it together" .PP .Vb 7 \& # base.t \& use strict; \& use warnings; \& use Test::More; \& use Plack::Test; \& use HTTP::Request::Common; \& use MyApp; \& \& my $test = Plack::Test\->create( MyApp\->to_app ); \& my $response = $test\->request( GET \*(Aq/\*(Aq ); \& \& ok( $response\->is_success, \*(Aq[GET /] Successful request\*(Aq ); \& is( $response\->content, \*(AqOK\*(Aq, \*(Aq[GET /] Correct content\*(Aq ); \& \& done_testing(); .Ve .PP \fISubtests\fR .IX Subsection "Subtests" .PP Tests can be separated using Test::More's \f(CW\*(C`subtest\*(C'\fR functionality, thus creating multiple self-contained tests that don't overwrite each other. .PP Assuming we have a different app that has two states we want to test: .PP .Vb 4 \& # MyApp.pm \& package MyApp; \& use Dancer2; \& set serializer => \*(AqJSON\*(Aq; \& \& get \*(Aq/:user\*(Aq => sub { \& my $user = route_parameters\->get(\*(Aquser\*(Aq); \& \& $user and return { user => $user }; \& \& return {}; \& }; \& \& 1; .Ve .PP This is a contrived example of a route that checks for a user parameter. If it exists, it returns it in a hash with the key \&'user'. If not, it returns an empty hash .PP .Vb 7 \& # param.t \& use strict; \& use warnings; \& use Test::More; \& use Plack::Test; \& use HTTP::Request::Common; \& use MyApp; \& \& my $test = Plack::Test\->create( MyApp\->to_app ); \& \& subtest \*(AqA empty request\*(Aq => sub { \& my $res = $test\->request( GET \*(Aq/\*(Aq ); \& ok( $res\->is_success, \*(AqSuccessful request\*(Aq ); \& is( $res\->content \*(Aq{}\*(Aq, \*(AqEmpty response back\*(Aq ); \& }; \& \& subtest \*(AqRequest with user\*(Aq => sub { \& my $res = $test\->request( GET \*(Aq/?user=sawyer_x\*(Aq ); \& ok( $res\->is_success, \*(AqSuccessful request\*(Aq ); \& is( $res\->content \*(Aq{"user":"sawyer_x"}\*(Aq, \*(AqEmpty response back\*(Aq ); \& }; \& \& done_testing(); .Ve .PP \fICookies\fR .IX Subsection "Cookies" .PP To handle cookies, which are mostly used for maintaining sessions, the following modules can be used: .IP "\(bu" 4 Test::WWW::Mechanize::PSGI .IP "\(bu" 4 LWP::Protocol::PSGI .IP "\(bu" 4 HTTP::Cookies .PP Taking the previous test, assuming it actually creates and uses cookies for sessions: .PP .Vb 2 \& # ... all the use statements \& use HTTP::Cookies; \& \& my $jar = HTTP::Cookies\->new; \& my $test = Plack::Test\->create( MyApp\->to_app ); \& \& subtest \*(AqA empty request\*(Aq => sub { \& my $res = $test\->request( GET \*(Aq/\*(Aq ); \& ok( $res\->is_success, \*(AqSuccessful request\*(Aq ); \& is( $res\->content \*(Aq{}\*(Aq, \*(AqEmpty response back\*(Aq ); \& $jar\->extract_cookies($res); \& ok( $jar\->as_string, \*(AqWe have cookies!\*(Aq ); \& }; \& \& subtest \*(AqRequest with user\*(Aq => sub { \& my $req = GET \*(Aq/?user=sawyer_x\*(Aq; \& $jar\->add_cookie_header($req); \& my $res = $test\->request($req); \& ok( $res\->is_success, \*(AqSuccessful request\*(Aq ); \& is( $res\->content \*(Aq{"user":"sawyer_x"}\*(Aq, \*(AqEmpty response back\*(Aq ); \& $jar\->extract_cookies($res); \& \& ok( ! $jar\->as_string, \*(AqAll cookies deleted\*(Aq ); \& }; \& \& done_testing(); .Ve .PP Here a cookie jar is created, all requests and responses, existing cookies, as well as cookies that were deleted by the response, are checked. .PP \fIAccessing the configuration file\fR .IX Subsection "Accessing the configuration file" .PP By importing Dancer2 in the command line scripts, there is full access to the configuration using the imported keywords: .PP .Vb 7 \& use strict; \& use warnings; \& use Test::More; \& use Plack::Test; \& use HTTP::Request::Common; \& use MyApp; \& use Dancer2; \& \& my $appname = config\->{\*(Aqappname\*(Aq}; \& diag "Testing $appname"; \& \& # ... .Ve .SH "PACKAGING" .IX Header "PACKAGING" .SS "Carton" .IX Subsection "Carton" \fIWhat it does\fR .IX Subsection "What it does" .PP Carton sets up a local copy of your project prerequisites. You only need to define them in a file and ask Carton to download all of them and set them up. When you want to deploy your app, you just carry the git clone and ask Carton to set up the environment again and you will then be able to run it. .PP The benefits are multifold: .IP "\(bu" 4 Local Directory copy .Sp By putting all the dependencies in a local directory, you can make sure they aren't updated by someone else by accident and their versions locked to the version you picked. .IP "\(bu" 4 Sync versions .Sp Deciding which versions of the dependent modules your project needs allows you to sync this with other developers as well. Now you're all using the same version and they don't change unless you want update the versions you want. When updated everyone again uses the same new version of everything. .IP "\(bu" 4 Carry only the requirement, not bundled modules .Sp Instead of bundling the modules, you only actually bundle the requirements. Carton builds them for you when you need it. .PP \fISetting it up\fR .IX Subsection "Setting it up" .PP First set up a new app: .PP .Vb 2 \& $ dancer2 \-a MyApp \& ... .Ve .PP Delete the files that are not needed: .PP .Vb 1 \& $ rm \-f Makefile.PL MANIFEST MANIFEST.SKIP .Ve .PP Create a git repo: .PP .Vb 1 \& $ git init && git add . && git commit \-m "initial commit" .Ve .PP Add a requirement using the cpanfile format: .PP .Vb 6 \& $ cat > cpanfile \& requires \*(AqDancer2\*(Aq => 0.155000; \& requires \*(AqTemplate\*(Aq => 0; \& recommends \*(AqURL::Encode::XS\*(Aq => 0; \& recommends \*(AqCGI::Deurl::XS\*(Aq => 0; \& recommends \*(AqHTTP::Parser::XS\*(Aq => 0; .Ve .PP Ask carton to set it up: .PP .Vb 5 \& $ carton install \& Installing modules using [...] \& Successfully installed [...] \& ... \& Complete! Modules were install into [...]/local .Ve .PP Now we have two files: \fIcpanfile\fR and \fIcpanfile.snapshot\fR. We add both of them to our Git repository and we make sure we don't accidentally add the \fIlocal/\fR directory Carton created which holds the modules it installed: .PP .Vb 3 \& $ echo local/ >> .gitignore \& $ git add .gitignore cpanfile cpanfile.snapshot \& $ git commit \-m "Start using carton" .Ve .PP When we want to update the versions on the production machine, we simply call: .PP .Vb 1 \& $ carton install \-\-deployment .Ve .PP By using \-\-deployment we make sure we only install the modules we have in our cpanfile.snapshot file and do not fallback to querying the \s-1CPAN.\s0 .SS "FatPacker" .IX Subsection "FatPacker" App::FatPacker (using its command line interface, fatpack) packs dependencies into a single file, allowing you to carry a single file instead of a directory tree. .PP As long as your application is pure-Perl, you could create a single file with your application and all of Dancer2 in it. .PP The following example will demonstrate how this can be done: .PP Assuming we have an application in \fIlib/MyApp.pm\fR: .PP .Vb 4 \& package MyApp; \& use Dancer2; \& get \*(Aq/\*(Aq => sub {\*(AqOK\*(Aq}; \& 1; .Ve .PP And we have a handler in \fIbin/app.pl\fR: .PP .Vb 5 \& use strict; \& use warnings; \& use FindBin; \& use lib "$FindBin::Bin/../lib"; \& use MyApp; \& \& MyApp\->to_app; .Ve .PP To fatpack it, we begin by tracing the script: .PP .Vb 1 \& $ fatpack trace bin/app.pl .Ve .PP This creates a \fIfatpacker.trace\fR file. From this we create the packlists: .PP .Vb 1 \& $ fatpack packlists\-for \`cat fatpacker.trace\` > packlists .Ve .PP The packlists are stored in a file called \fIpacklists\fR. .PP Now we create the tree using the following command: .PP .Vb 1 \& $ fatpack tree \`cat packlists\` .Ve .PP The tree is created under the directory \fIfatlib\fR. .PP Now we create a file containing the dependency tree, and add our script to it, using the following command: .PP .Vb 1 \& $ (fatpack file; cat bin/app.pl) > myapp.pl .Ve .PP This creates a file called \fImyapp.pl\fR with everything in it. Dancer2 uses MIME::Types which has a database of all \s-1MIME\s0 types and helps translate those. The small database file containing all of these types is a binary and therefore cannot be fatpacked. Hence, it needs to be copied to the current directory so our script can find it: .PP .Vb 1 \& $ cp fatlib/MIME/types.db . .Ve .SH "MIDDLEWARES" .IX Header "MIDDLEWARES" .SS "Plack middlewares" .IX Subsection "Plack middlewares" If you want to use Plack middlewares, you need to enable them using Plack::Builder as such: .PP .Vb 3 \& # in app.psgi or any other handler \& use MyApp; \& use Plack::Builder; \& \& builder { \& enable \*(AqDeflater\*(Aq; \& enable \*(AqSession\*(Aq, store => \*(AqFile\*(Aq; \& enable \*(AqDebug\*(Aq, panels => [ qw ]; \& MyApp\->to_app; \& }; .Ve .PP The nice thing about this setup is that it will work seamlessly through Plack or through the internal web server. .PP .Vb 2 \& # load dev web server (without middlewares) \& perl \-Ilib app.psgi \& \& # load plack web server (with middlewares) \& plackup \-I lib app.psgi .Ve .PP You do not need to provide different files for either server. .PP \fIPath-based middlewares\fR .IX Subsection "Path-based middlewares" .PP If you want to set up a middleware for a specific path, you can do that using Plack::Builder which uses Plack::App::URLMap: .PP .Vb 3 \& # in your app.psgi or any other handler \& use MyApp; \& use Plack::Builder; \& \& my $special_handler = sub { ... }; \& \& builder { \& mount \*(Aq/special\*(Aq => $special_handler; \& mount \*(Aq/\*(Aq => MyApp\->to_app; \& }; .Ve .PP \fIRemoving default middlewares\fR .IX Subsection "Removing default middlewares" .PP By default, a Dancer2 app is automatically wrapped with the following middleware .IP "\(bu" 4 Plack::Middleware::FixMissingBodyInRedirect .IP "\(bu" 4 Plack::Middleware::Head .PP You can configure the setting \f(CW\*(C`no_default_middleware\*(C'\fR to a true value to stop your Dancer2 app being wrapped with these default middleware layers. .PP .Vb 3 \& # in you Dancer2 app or config.yml \& package MyApp; \& use Dancer2 \& \& set no_default_middleware => true; .Ve .PP This is necessary if you need to add eTag or ContentMD5 headers to \&\f(CW\*(C`HEAD\*(C'\fR requests, and you are encouraged to manually add those default middleware back into your \s-1PSGI\s0 stack. .PP \fIRunning on Perl web servers with plackup\fR .IX Subsection "Running on Perl web servers with plackup" .PP A number of Perl web servers supporting \s-1PSGI\s0 are available on \s-1CPAN:\s0 .IP "\(bu" 4 Starman .Sp \&\f(CW\*(C`Starman\*(C'\fR is a high performance web server, with support for preforking, signals, multiple interfaces, graceful restarts and dynamic worker pool configuration. .IP "\(bu" 4 Twiggy .Sp \&\f(CW\*(C`Twiggy\*(C'\fR is an \f(CW\*(C`AnyEvent\*(C'\fR web server, it's light and fast. .IP "\(bu" 4 Corona .Sp \&\f(CW\*(C`Corona\*(C'\fR is a \f(CW\*(C`Coro\*(C'\fR based web server. .PP To start your application, just run plackup (see Plack and specific servers above for all available options): .PP .Vb 2 \& $ plackup bin/app.psgi \& $ plackup \-E deployment \-s Starman \-\-workers=10 \-p 5001 \-a bin/app.psgi .Ve .PP As you can see, the scaffolded Perl script for your app can be used as a \&\s-1PSGI\s0 startup file. .PP Enabling content compression .IX Subsection "Enabling content compression" .PP Content compression (gzip, deflate) can be easily enabled via a Plack middleware (see \*(L"Plack::Middleware\*(R" in Plack): Plack::Middleware::Deflater. It's a middleware to encode the response body in gzip or deflate, based on the \&\f(CW\*(C`Accept\-Encoding\*(C'\fR \s-1HTTP\s0 request header. .PP Enable it as you would enable any Plack middleware. First you need to install Plack::Middleware::Deflater, then in the handler (usually \&\fIapp.psgi\fR) edit it to use Plack::Builder, as described above: .PP .Vb 3 \& use Dancer2; \& use MyApp; \& use Plack::Builder; \& \& builder { \& enable \*(AqDeflater\*(Aq; \& MyApp\->to_app; \& }; .Ve .PP To test if content compression works, trace the \s-1HTTP\s0 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 \&\f(CW\*(C`Content\-Encoding\*(C'\fR set to \f(CW\*(C`gzip\*(C'\fR or \f(CW\*(C`deflate\*(C'\fR. .PP \fIRunning multiple apps with Plack::Builder\fR .IX Subsection "Running multiple apps with Plack::Builder" .PP You can use Plack::Builder to mount multiple Dancer2 applications on a \&\s-1PSGI\s0 webserver like Starman. .PP Start by creating a simple app.psgi file: .PP .Vb 3 \& use OurWiki; # first app \& use OurForum; # second app \& use Plack::Builder; \& \& builder { \& mount \*(Aq/wiki\*(Aq => OurWiki\->to_app; \& mount \*(Aq/forum\*(Aq => OurForum\->to_app; \& }; .Ve .PP and now use Starman .PP .Vb 1 \& plackup \-a app.psgi \-s Starman .Ve .PP 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. .PP \fIRunning from Apache with Plack\fR .IX Subsection "Running from Apache with Plack" .PP You can run your app from Apache using \s-1PSGI\s0 (Plack), with a config like the following: .PP .Vb 4 \& \& ServerName www.myapp.example.com \& ServerAlias myapp.example.com \& DocumentRoot /websites/myapp.example.com \& \& \& AllowOverride None \& Order allow,deny \& Allow from all \& \& \& \& SetHandler perl\-script \& PerlResponseHandler Plack::Handler::Apache2 \& PerlSetVar psgi_app /websites/myapp.example.com/app.psgi \& \& \& ErrorLog /websites/myapp.example.com/logs/error_log \& CustomLog /websites/myapp.example.com/logs/access_log common \& .Ve .PP To set the environment you want to use for your application (production or development), you can set it this way: .PP .Vb 5 \& \& ... \& SetEnv DANCER_ENVIRONMENT "production" \& ... \& .Ve .SH "PLUGINS" .IX Header "PLUGINS" .SS "Writing a plugin" .IX Subsection "Writing a plugin" See \*(L"Writing the plugin\*(R" in Dancer2::Plugin for information on how to author a new plugin for Dancer2. .SH "EXPORTS" .IX Header "EXPORTS" By default, \f(CW\*(C`use Dancer2\*(C'\fR exports all the \s-1DSL\s0 keywords and sets up the webapp under the name of the current package. The following tags control exports and webapp namespace. .IP "\(bu" 4 \&\fB!keyword\fR .Sp If you want to prevent Dancer2 from exporting specific keywords (perhaps you plan to implement them yourself in a different way, or they clash with another module you're loading), you can simply exclude them: .Sp .Vb 2 \& use Test::More; \& use Dancer2 qw(!pass); .Ve .Sp The above would import all keywords as usual, with the exception of \f(CW\*(C`pass\*(C'\fR. .IP "\(bu" 4 \&\fBappname\fR .Sp A larger application may split its source between several packages to aid maintainability. Dancer2 will create a separate application for each package, each having separate hooks, config and/or engines. You can force Dancer2 to collect the route and hooks into a single application with the \&\f(CW\*(C`appname\*(C'\fR tag; e.g. .Sp .Vb 3 \& package MyApp; \& use Dancer2; \& get \*(Aq/foo\*(Aq => sub {...}; \& \& package MyApp::Private; \& use Dancer2 appname => MyApp; \& get \*(Aq/bar\*(Aq => sub {...}; .Ve .Sp The above would add the \f(CW\*(C`bar\*(C'\fR route to the MyApp application. Dancer2 will \&\fInot\fR create an application with the name \f(CW\*(C`MyApp::Private\*(C'\fR. .IP "\(bu" 4 \&\fB:nopragmas\fR .Sp By default Dancer2 will import three pragmas: strict, warnings, and utf8. If you require control over the imported pragmas, you can add \&\fB:nopragmas\fR to the importing flags, in which case Dancer2 will not import any pragmas: .Sp .Vb 4 \& use strict; \& use warnings; \& no warnings \*(Aqexperimental::smartmatch\*(Aq; # for example... \& use Dancer2 \*(Aq:nopragmas\*(Aq; # do not touch the existing pragmas .Ve .Sp This way importing \f(CW\*(C`Dancer2\*(C'\fR does not change the existing pragmas setup you have. .PP When you \f(CW\*(C`use Dancer2\*(C'\fR, you get an \f(CW\*(C`import\*(C'\fR method added into the current package. This \fBwill\fR override previously declared import methods from other sources, such as Exporter. Dancer2 applications support the following tags on import: .IP "\(bu" 4 \&\fBwith\fR .Sp The \f(CW\*(C`with\*(C'\fR tag allows an app to pass one or more config entries to another app, when it \f(CW\*(C`use\*(C'\fRs it. .Sp .Vb 2 \& package MyApp; \& use Dancer2; \& \& BEGIN { set session => \*(AqYAML\*(Aq }; \& use Blog with => { session => engine(\*(Aqsession\*(Aq) }; .Ve .Sp In this example, the session engine is passed to the \f(CW\*(C`Blog\*(C'\fR app. That way, anything done in the session will be shared between both apps. .Sp Anything that is defined in the config entry can be passed that way. If we want to pass the whole config object, it can be done like so: .Sp .Vb 1 \& use SomeApp with => { %{config()} }; .Ve .SH "DSL KEYWORDS" .IX Header "DSL KEYWORDS" Dancer2 provides you with a \s-1DSL\s0 (Domain-Specific Language) which makes implementing your web application trivial. .PP For example, take the following example: .PP .Vb 1 \& use Dancer2; \& \& get \*(Aq/hello/:name\*(Aq => sub { \& my $name = route_parameters\->get(\*(Aqname\*(Aq); \& }; \& dance; .Ve .PP \&\f(CW\*(C`get\*(C'\fR and \f(CW\*(C`route_parameters\*(C'\fR are keywords provided by Dancer2. .PP This document lists all keywords provided by Dancer2. It does not cover additional keywords which may be provided by loaded plugins; see the documentation for plugins you use to see which additional keywords they make available to you. .SS "any" .IX Subsection "any" Defines a route for multiple \s-1HTTP\s0 methods at once: .PP .Vb 3 \& any [\*(Aqget\*(Aq, \*(Aqpost\*(Aq] => \*(Aq/myaction\*(Aq => sub { \& # code \& }; .Ve .PP Or even, a route handler that would match any \s-1HTTP\s0 methods: .PP .Vb 3 \& any \*(Aq/myaction\*(Aq => sub { \& # code \& }; .Ve .SS "cookies" .IX Subsection "cookies" Accesses cookies values, it returns a hashref of Dancer2::Core::Cookie objects: .PP .Vb 4 \& get \*(Aq/some_action\*(Aq => sub { \& my $cookie = cookies\->{name}; \& return $cookie\->value; \& }; .Ve .PP In case you have stored something other than a scalar in your cookie: .PP .Vb 5 \& get \*(Aq/some_action\*(Aq => sub { \& my $cookie = cookies\->{oauth}; \& my %values = $cookie\->value; \& return ($values{token}, $values{token_secret}); \& }; .Ve .SS "cookie" .IX Subsection "cookie" Accesses a cookie value (or sets it). Note that this method will eventually be preferred over \f(CW\*(C`set_cookie\*(C'\fR. .PP .Vb 3 \& cookie lang => "fr\-FR"; # set a cookie and return its value \& cookie lang => "fr\-FR", expires => "2 hours"; # extra cookie info \& cookie "lang" # return a cookie value .Ve .PP If your cookie value is a key/value \s-1URI\s0 string, like .PP .Vb 1 \& token=ABC&user=foo .Ve .PP \&\f(CW\*(C`cookie\*(C'\fR will only return the first part (\f(CW\*(C`token=ABC\*(C'\fR) if called in scalar context. Use list context to fetch them all: .PP .Vb 1 \& my @values = cookie "name"; .Ve .SS "config" .IX Subsection "config" Accesses the configuration of the application: .PP .Vb 3 \& get \*(Aq/appname\*(Aq => sub { \& return "This is " . config\->{appname}; \& }; .Ve .SS "content" .IX Subsection "content" Sets the content for the response. This \fBonly\fR works within a delayed response. .PP This will crash: .PP .Vb 4 \& get \*(Aq/\*(Aq => sub { \& # THIS WILL CRASH \& content \*(AqHello, world!\*(Aq; \& }; .Ve .PP But this will work just fine: .PP .Vb 6 \& get \*(Aq/\*(Aq => sub { \& delayed { \& content \*(AqHello, world!\*(Aq; \& ... \& }; \& }; .Ve .SS "content_type" .IX Subsection "content_type" Sets the \fBcontent-type\fR rendered, for the current route handler: .PP .Vb 2 \& get \*(Aq/cat/:txtfile\*(Aq => sub { \& content_type \*(Aqtext/plain\*(Aq; \& \& # here we can dump the contents of route_parameters\->get(\*(Aqtxtfile\*(Aq) \& }; .Ve .PP You can use abbreviations for content types. For instance: .PP .Vb 2 \& get \*(Aq/svg/:id\*(Aq => sub { \& content_type \*(Aqsvg\*(Aq; \& \& # here we can dump the image with id route_parameters\->get(\*(Aqid\*(Aq) \& }; .Ve .PP Note that if you want to change the default content-type for every route, it is easier to change the \f(CW\*(C`content_type\*(C'\fR setting instead. .SS "dance" .IX Subsection "dance" Alias for the \f(CW\*(C`start\*(C'\fR keyword. .SS "dancer_version" .IX Subsection "dancer_version" Returns the version of Dancer. If you need the major version, do something like: .PP .Vb 1 \& int(dancer_version); .Ve .SS "debug" .IX Subsection "debug" Logs a message of debug level: .PP .Vb 1 \& debug "This is a debug message"; .Ve .PP See Dancer2::Core::Role::Logger for details on how to configure where log messages go. .SS "decode_json ($string)" .IX Subsection "decode_json ($string)" Deserializes a \s-1JSON\s0 structure from an \s-1UTF\-8\s0 binary string. .SS "dirname" .IX Subsection "dirname" Returns the dirname of the path given: .PP .Vb 1 \& my $dir = dirname($some_path); .Ve .SS "encode_json ($structure)" .IX Subsection "encode_json ($structure)" Serializes a structure to a \s-1UTF\-8\s0 binary \s-1JSON\s0 string. .PP Calling this function will \fBnot\fR trigger the serialization's hooks. .SS "engine" .IX Subsection "engine" Given a namespace, returns the current engine object .PP .Vb 3 \& my $template_engine = engine \*(Aqtemplate\*(Aq; \& my $html = $template_engine\->apply_renderer(...); \& $template_engine\->apply_layout($html); .Ve .SS "error" .IX Subsection "error" Logs a message of error level: .PP .Vb 1 \& error "This is an error message"; .Ve .PP See Dancer2::Core::Role::Logger for details on how to configure where log messages go. .SS "false" .IX Subsection "false" Constant that returns a false value (0). .SS "forward" .IX Subsection "forward" Runs an \*(L"internal redirect\*(R" of the current route to another route. More formally; when \f(CW\*(C`forward\*(C'\fR is executed, the current dispatch of the route is aborted, the request is modified (altering query params or request method), and the modified request following a new route is dispatched again. Any remaining code (route and hooks) from the current dispatch will never be run and the modified route's dispatch will execute hooks for the new route normally. .PP It effectively lets you chain routes together in a clean manner. .PP .Vb 1 \& get \*(Aq/demo/articles/:article_id\*(Aq => sub { \& \& # you\*(Aqll have to implement this next sub yourself :) \& change_the_main_database_to_demo(); \& \& forward "/articles/" . route_parameters\->get(\*(Aqarticle_id\*(Aq); \& }; .Ve .PP In the above example, the users that reach \fI/demo/articles/30\fR will actually reach \fI/articles/30\fR but we've changed the database to demo before. .PP This is pretty cool because it lets us retain our paths and offer a demo database by merely going to \fI/demo/...\fR. .PP You'll notice that in the example we didn't indicate whether it was \fB\s-1GET\s0\fR or \fB\s-1POST\s0\fR. That is because \f(CW\*(C`forward\*(C'\fR chains the same type of route the user reached. If it was a \fB\s-1GET\s0\fR, it will remain a \fB\s-1GET\s0\fR (but if you do need to change the method, you can do so; read on below for details.) .PP Also notice that \f(CW\*(C`forward\*(C'\fR only redirects to a new route. It does not redirect the requests involving static files. This is because static files are handled before Dancer2 tries to match the request to a route \- static files take higher precedence. .PP This means that you will not be able to \f(CW\*(C`forward\*(C'\fR to a static file. If you wish to do so, you have two options: either redirect (asking the browser to make another request, but to a file path instead) or use \f(CW\*(C`send_file\*(C'\fR to provide a file. .PP \&\fB\s-1WARNING:\s0\fR Any code after a \f(CW\*(C`forward\*(C'\fR is ignored, until the end of the route. It's not necessary to use \f(CW\*(C`return\*(C'\fR with \f(CW\*(C`forward\*(C'\fR anymore. .PP .Vb 6 \& get \*(Aq/foo/:article_id\*(Aq => sub { \& if ($condition) { \& forward "/articles/" . route_parameters\->get(\*(Aqarticle_id\*(Aq); \& # The following code WILL NOT BE executed \& do_stuff(); \& } \& \& more_stuff(); \& }; .Ve .PP Note that \f(CW\*(C`forward\*(C'\fR doesn't parse \s-1GET\s0 arguments. So, you can't use something like: .PP .Vb 1 \& forward \*(Aq/home?authorized=1\*(Aq; .Ve .PP But \f(CW\*(C`forward\*(C'\fR supports an optional hashref with parameters to be added to the actual parameters: .PP .Vb 1 \& forward \*(Aq/home\*(Aq, { authorized => 1 }; .Ve .PP Finally, you can add some more options to the \f(CW\*(C`forward\*(C'\fR method, in a third argument, also as a hashref. That option is currently only used to change the method of your request. Use with caution. .PP .Vb 1 \& forward \*(Aq/home\*(Aq, { auth => 1 }, { method => \*(AqPOST\*(Aq }; .Ve .SS "from_dumper ($structure)" .IX Subsection "from_dumper ($structure)" Deserializes a Data::Dumper structure. .SS "from_json ($string, \e%options)" .IX Subsection "from_json ($string, %options)" Deserializes a \s-1JSON\s0 structure from a string. You should probably use \&\f(CW\*(C`decode_json\*(C'\fR which expects a \s-1UTF\-8\s0 encoded binary string and handles decoding it for you. .SS "from_yaml ($structure)" .IX Subsection "from_yaml ($structure)" Deserializes a \s-1YAML\s0 structure. .SS "get" .IX Subsection "get" Defines a route for \s-1HTTP\s0 \fB\s-1GET\s0\fR requests to the given path: .PP .Vb 3 \& get \*(Aq/\*(Aq => sub { \& return "Hello world"; \& } .Ve .PP Note that a route to match \fB\s-1HEAD\s0\fR requests is automatically created as well. .SS "halt" .IX Subsection "halt" Sets a response object with the content given. .PP When used as a return value from a hook, this breaks the execution flow and renders the response immediately: .PP .Vb 3 \& hook before => sub { \& if ($some_condition) { \& halt("Unauthorized"); \& \& # this code is not executed \& do_stuff(); \& } \& }; \& \& get \*(Aq/\*(Aq => sub { \& "hello there"; \& }; .Ve .PP \&\fB\s-1WARNING:\s0\fR Issuing a halt immediately exits the current route, and performs the halt. Thus, any code after a halt is ignored, until the end of the route. Hence, it's not necessary anymore to use \f(CW\*(C`return\*(C'\fR with halt. .SS "response_headers" .IX Subsection "response_headers" Adds custom headers to response: .PP .Vb 3 \& get \*(Aq/send/headers\*(Aq, sub { \& response_headers \*(AqX\-Foo\*(Aq => \*(Aqbar\*(Aq, \*(AqX\-Bar\*(Aq => \*(Aqfoo\*(Aq; \& } .Ve .SS "response_header" .IX Subsection "response_header" Adds a custom header to response: .PP .Vb 3 \& get \*(Aq/send/header\*(Aq, sub { \& response_header \*(Aqx\-my\-header\*(Aq => \*(Aqshazam!\*(Aq; \& } .Ve .PP Note that it will overwrite the old value of the header, if any. To avoid that, see \*(L"push_response_header\*(R". .SS "push_response_header" .IX Subsection "push_response_header" Do the same as \f(CW\*(C`response_header\*(C'\fR, but allow for multiple headers with the same name. .PP .Vb 5 \& get \*(Aq/send/header\*(Aq, sub { \& push_response_header \*(Aqx\-my\-header\*(Aq => \*(Aq1\*(Aq; \& push_response_header \*(Aqx\-my\-header\*(Aq => \*(Aq2\*(Aq; \& # will result in two headers "x\-my\-header" in the response \& } .Ve .SS "prepare_app" .IX Subsection "prepare_app" You can introduce code you want to run when your app is loaded, similar to the \&\f(CW\*(C`prepare_app\*(C'\fR in Plack::Middleware. .PP .Vb 2 \& prepare_app { \& my $app = shift; \& \& ... # do your thing \& }; .Ve .PP You should not close over the App instance, since you receive it as a first argument. If you close over it, you \fBwill\fR have a memory leak. .PP .Vb 1 \& my $app = app(); \& \& prepare_app { \& do_something_with_app($app); # MEMORY LEAK \& }; .Ve .SS "hook" .IX Subsection "hook" Adds a hook at some position. For example : .PP .Vb 4 \& hook before_serializer => sub { \& my $content = shift; \& ... \& }; .Ve .PP There can be multiple hooks assigned to a given position, and each will be executed in order. .PP See the \s-1HOOKS\s0 section for a list of available hooks. .SS "info" .IX Subsection "info" Logs a message of \f(CW\*(C`info\*(C'\fR level: .PP .Vb 1 \& info "This is an info message"; .Ve .PP See Dancer2::Core::Role::Logger for details on how to configure where log messages go. .SS "mime" .IX Subsection "mime" Shortcut to access the instance object of Dancer2::Core::MIME. You should read the Dancer2::Core::MIME documentation for full details, but the most commonly-used methods are summarized below: .PP .Vb 2 \& # set a new mime type \& mime\->add_type( foo => \*(Aqtext/foo\*(Aq ); \& \& # set a mime type alias \& mime\->add_alias( f => \*(Aqfoo\*(Aq ); \& \& # get mime type for an alias \& my $m = mime\->for_name( \*(Aqf\*(Aq ); \& \& # get mime type for a file (based on extension) \& my $m = mime\->for_file( "foo.bar" ); \& \& # get current defined default mime type \& my $d = mime\->default; \& \& # set the default mime type using config.yml \& # or using the set keyword \& set default_mime_type => \*(Aqtext/plain\*(Aq; .Ve .SS "params" .IX Subsection "params" \&\fIThis method should be called from a route handler\fR. It's an alias for the Dancer2::Core::Request params accessor. It returns a hash (in list context) or a hash reference (in scalar context) to all defined parameters. Check \f(CW\*(C`param\*(C'\fR below to access quickly to a single parameter value. .PP .Vb 3 \& post \*(Aq/login\*(Aq => sub { \& # get all parameters as a single hash \& my %all_parameters = params; \& \& // request all parmameters from a specific source: body, query, route \& my %body_parameters = params(\*(Aqbody\*(Aq); \& my %route_parameters = params(\*(Aqroute\*(Aq); \& my %query_parameters = params(\*(Aqquery\*(Aq); \& \& # any $source that is not body, query, or route generates an exception \& params(\*(Aqfake_source\*(Aq); // Unknown source params "fake_source" \& }; .Ve .PP We now recommend using one of the specific keywords for parameters (\f(CW\*(C`route_parameters\*(C'\fR, \f(CW\*(C`query_parameters\*(C'\fR, and \f(CW\*(C`body_parameters\*(C'\fR) instead of \f(CW\*(C`params\*(C'\fR or \f(CW\*(C`param\*(C'\fR. .SS "param" .IX Subsection "param" \&\fIThis method should be called from a route handler\fR. This method is an accessor to the parameters hash table. .PP .Vb 5 \& post \*(Aq/login\*(Aq => sub { \& my $username = param "user"; \& my $password = param "pass"; \& # ... \& }; .Ve .PP We now recommend using one of the specific keywords for parameters (\f(CW\*(C`route_parameters\*(C'\fR, \f(CW\*(C`query_parameters\*(C'\fR, and \f(CW\*(C`body_parameters\*(C'\fR) instead of \f(CW\*(C`params\*(C'\fR or \f(CW\*(C`param\*(C'\fR. .SS "route_parameters" .IX Subsection "route_parameters" Returns a Hash::MultiValue object from the route parameters. .PP .Vb 4 \& # /hello \& get \*(Aq/:foo\*(Aq => sub { \& my $foo = route_parameters\->get(\*(Aqfoo\*(Aq); \& }; .Ve .SS "query_parameters" .IX Subsection "query_parameters" Returns a Hash::MultiValue object from the request parameters. .PP .Vb 4 \& /?foo=hello \& get \*(Aq/\*(Aq => sub { \& my $name = query_parameters\->get(\*(Aqfoo\*(Aq); \& }; \& \& /?name=Alice&name=Bob \& get \*(Aq/\*(Aq => sub { \& my @names = query_parameters\->get_all(\*(Aqname\*(Aq); \& }; .Ve .SS "body_parameters" .IX Subsection "body_parameters" Returns a Hash::MultiValue object from the body parameters. .PP .Vb 4 \& post \*(Aq/\*(Aq => sub { \& my $last_name = body_parameters\->get(\*(Aqname\*(Aq); \& my @all_names = body_parameters\->get_all(\*(Aqname\*(Aq); \& }; .Ve .SS "pass" .IX Subsection "pass" \&\fIThis method should be called from a route handler\fR. Tells Dancer2 to pass the processing of the request to the next matching route. .PP \&\fB\s-1WARNING:\s0\fR Issuing a pass immediately exits the current route, and performs the pass. Thus, any code after a pass is ignored, until the end of the route. Hence, it's not necessary anymore to use \f(CW\*(C`return\*(C'\fR with pass. .PP .Vb 4 \& get \*(Aq/some/route\*(Aq => sub { \& if (...) { \& # we want to let the next matching route handler process this one \& pass(...); \& \& # this code will be ignored \& do_stuff(); \& } \& }; .Ve .PP \&\fB\s-1WARNING:\s0\fR You cannot set the content before passing and have it remain, even if you use the \f(CW\*(C`content\*(C'\fR keyword or set it directly in the response object. .SS "patch" .IX Subsection "patch" Defines a route for \s-1HTTP\s0 \fB\s-1PATCH\s0\fR requests to the given \s-1URL:\s0 .PP .Vb 1 \& patch \*(Aq/resource\*(Aq => sub { ... }; .Ve .PP (\f(CW\*(C`PATCH\*(C'\fR is a relatively new and not-yet-common \s-1HTTP\s0 verb, which is intended to work as a \*(L"partial-PUT\*(R", transferring just the changes; please see \s-1RFC5789\s0 for further details.) .SS "path" .IX Subsection "path" Concatenates multiple paths together, without worrying about the underlying operating system: .PP .Vb 1 \& my $path = path(dirname($0), \*(Aqlib\*(Aq, \*(AqFile.pm\*(Aq); .Ve .PP It also normalizes (cleans) the path aesthetically. It does not verify whether the path exists, though. .SS "post" .IX Subsection "post" Defines a route for \s-1HTTP\s0 \fB\s-1POST\s0\fR requests to the given \s-1URL:\s0 .PP .Vb 3 \& post \*(Aq/\*(Aq => sub { \& return "Hello world"; \& } .Ve .SS "prefix" .IX Subsection "prefix" Defines a prefix for each route handler, like this: .PP .Vb 1 \& prefix \*(Aq/home\*(Aq; .Ve .PP From here, any route handler is defined to /home/*: .PP .Vb 1 \& get \*(Aq/page1\*(Aq => sub {}; # will match \*(Aq/home/page1\*(Aq .Ve .PP You can unset the prefix value: .PP .Vb 2 \& prefix undef; \& get \*(Aq/page1\*(Aq => sub {}; # will match /page1 .Ve .PP For a safer alternative you can use lexical prefix like this: .PP .Vb 2 \& prefix \*(Aq/home\*(Aq => sub { \& ## Prefix is set to \*(Aq/home\*(Aq here \& \& get ...; \& get ...; \& }; \& ## prefix reset to the previous version here .Ve .PP This makes it possible to nest prefixes: .PP .Vb 2 \& prefix \*(Aq/home\*(Aq => sub { \& ## some routes \& \& prefix \*(Aq/private\*(Aq => sub { \& ## here we are under /home/private... \& \& ## some more routes \& }; \& ## back to /home \& }; \& ## back to the root .Ve .PP \&\fBNotice:\fR Once you have a prefix set, do not add a caret to the regex: .PP .Vb 3 \& prefix \*(Aq/foo\*(Aq; \& get qr{^/bar} => sub { ... } # BAD BAD BAD \& get qr{/bar} => sub { ... } # Good! .Ve .SS "del" .IX Subsection "del" Defines a route for \s-1HTTP\s0 \fB\s-1DELETE\s0\fR requests to the given \s-1URL:\s0 .PP .Vb 1 \& del \*(Aq/resource\*(Aq => sub { ... }; .Ve .SS "options" .IX Subsection "options" Defines a route for \s-1HTTP\s0 \fB\s-1OPTIONS\s0\fR requests to the given \s-1URL:\s0 .PP .Vb 1 \& options \*(Aq/resource\*(Aq => sub { ... }; .Ve .SS "put" .IX Subsection "put" Defines a route for \s-1HTTP\s0 \fB\s-1PUT\s0\fR requests to the given \s-1URL:\s0 .PP .Vb 1 \& put \*(Aq/resource\*(Aq => sub { ... }; .Ve .SS "redirect" .IX Subsection "redirect" Generates a \s-1HTTP\s0 redirect (302). You can either redirect to a complete different site or within the application: .PP .Vb 4 \& get \*(Aq/twitter\*(Aq, sub { \& redirect \*(Aqhttp://twitter.com/me\*(Aq; \& # Any code after the redirect will not be executed. \& }; .Ve .PP \&\fB\s-1WARNING:\s0\fR Issuing a \f(CW\*(C`redirect\*(C'\fR immediately exits the current route. Thus, any code after a \f(CW\*(C`redirect\*(C'\fR is ignored, until the end of the route. Hence, it's not necessary anymore to use \f(CW\*(C`return\*(C'\fR with \f(CW\*(C`redirect\*(C'\fR. .PP You can also force Dancer to return a specific 300\-ish \s-1HTTP\s0 response code: .PP .Vb 3 \& get \*(Aq/old/:resource\*(Aq, sub { \& redirect \*(Aq/new/\*(Aq . route_parameters\->get(\*(Aqresource\*(Aq), 301; \& }; .Ve .SS "request" .IX Subsection "request" Returns a Dancer2::Core::Request object representing the current request. .PP See the Dancer2::Core::Request documentation for the methods you can call, for example: .PP .Vb 3 \& request\->referer; # value of the HTTP referer header \& request\->remote_address; # user\*(Aqs IP address \& request\->user_agent; # User\-Agent header value .Ve .SS "request_header" .IX Subsection "request_header" Returns request header(s). .PP .Vb 4 \& get \*(Aq/get/headers\*(Aq => sub { \& my $xfoo = request_header \*(AqX\-Foo\*(Aq; \& ... \& }; .Ve .SS "send_as" .IX Subsection "send_as" Allows the current route handler to return specific content types to the client using either a specified serializer or as html. .PP Any Dancer2 serializer may be used. The specified serializer class will be loaded if required, or an error generated if the class can not be found. Serializer configuration may be added to your apps \f(CW\*(C`engines\*(C'\fR configuration. .PP If \f(CW\*(C`html\*(C'\fR is specified, the content will be returned assuming it is \s-1HTML\s0 with appropriate \f(CW\*(C`Content\-Type\*(C'\fR headers and encoded using the apps configured \&\f(CW\*(C`charset\*(C'\fR (or \s-1UTF\-8\s0). .PP .Vb 2 \& set serializer => \*(AqYAML\*(Aq; \& set template => \*(AqTemplateToolkit\*(Aq; \& \& # returns html (not YAML) \& get \*(Aq/\*(Aq => sub { send_as html => template \*(Aqwelcome.tt\*(Aq }; \& \& # return json (not YAML) \& get \*(Aq/json\*(Aq => sub { \& send_as JSON => [ some => { data => \*(Aqstructure\*(Aq } ]; \& }; .Ve .PP \&\f(CW\*(C`send_as\*(C'\fR uses \*(L"send_file\*(R" to return the content immediately. You may pass any option \f(CW\*(C`send_file\*(C'\fR supports as an extra option. For example: .PP .Vb 5 \& # return json with a custom content_type header \& get \*(Aq/json\*(Aq => sub { \& send_as JSON => [ some => { data => \*(Aqstructure\*(Aq } ], \& { content_type => \*(Aqapplication/json; charset=UTF\-8\*(Aq }, \& }; .Ve .PP \&\fB\s-1WARNING:\s0\fR Issuing a send_as immediately exits the current route, and performs the \f(CW\*(C`send_as\*(C'\fR. Thus, any code after a \f(CW\*(C`send_as\*(C'\fR is ignored, until the end of the route. Hence, it's not necessary to use \f(CW\*(C`return\*(C'\fR with \f(CW\*(C`send_as\*(C'\fR. .PP .Vb 3 \& get \*(Aq/some/route\*(Aq => sub { \& if (...) { \& send_as JSON => $some_data; \& \& # this code will be ignored \& do_stuff(); \& } \& }; .Ve .SS "send_error" .IX Subsection "send_error" Returns a \s-1HTTP\s0 error. By default the \s-1HTTP\s0 code returned is 500: .PP .Vb 7 \& get \*(Aq/photo/:id\*(Aq => sub { \& if (...) { \& send_error("Not allowed", 403); \& } else { \& # return content \& } \& } .Ve .PP \&\fB\s-1WARNING:\s0\fR Issuing a send_error immediately exits the current route, and performs the \f(CW\*(C`send_error\*(C'\fR. Thus, any code after a \f(CW\*(C`send_error\*(C'\fR is ignored, until the end of the route. Hence, it's not necessary anymore to use \f(CW\*(C`return\*(C'\fR with \f(CW\*(C`send_error\*(C'\fR. .PP .Vb 4 \& get \*(Aq/some/route\*(Aq => sub { \& if (...) { \& # Something bad happened, stop immediately! \& send_error(..); \& \& # this code will be ignored \& do_stuff(); \& } \& }; .Ve .SS "send_file" .IX Subsection "send_file" Lets the current route handler send a file to the client. Note that the path of the file must be relative to the \fBpublic\fR directory unless you use the \&\f(CW\*(C`system_path\*(C'\fR option (see below). .PP .Vb 3 \& get \*(Aq/download/:file\*(Aq => sub { \& return send_file(route_parameters\->get(\*(Aqfile\*(Aq)); \& } .Ve .PP \&\fB\s-1WARNING:\s0\fR Issuing a \f(CW\*(C`send_file\*(C'\fR immediately exits the current route, and performs the \f(CW\*(C`send_file\*(C'\fR. Thus, any code after a \f(CW\*(C`send_file\*(C'\fR is ignored, until the end of the route. Hence, it's not necessary anymore to use \f(CW\*(C`return\*(C'\fR with \f(CW\*(C`send_file\*(C'\fR. .PP .Vb 4 \& get \*(Aq/some/route\*(Aq => sub { \& if (...) { \& # OK, send her what she wants... \& send_file(...); \& \& # this code will be ignored \& do_stuff(); \& } \& }; .Ve .PP \&\f(CW\*(C`send_file\*(C'\fR will use \s-1PSGI\s0 streaming if the server supports it (most, if not all, do). You can explicitly disable streaming by passing \&\f(CW\*(C`streaming => 0\*(C'\fR as an option to \f(CW\*(C`send_file\*(C'\fR. .PP .Vb 3 \& get \*(Aq/download/:file\*(Aq => sub { \& send_file( route_parameters\->get(\*(Aqfile\*(Aq), streaming => 0 ); \& } .Ve .PP The content-type will be set depending on the current \s-1MIME\s0 types definition (see \f(CW\*(C`mime\*(C'\fR if you want to define your own). .PP If your filename does not have an extension, you are passing in a filehandle, or you need to force a specific mime type, you can pass it to \f(CW\*(C`send_file\*(C'\fR as follows: .PP .Vb 2 \& send_file(route_parameters\->get(\*(Aqfile\*(Aq), content_type => \*(Aqimage/png\*(Aq); \& send_file($fh, content_type => \*(Aqimage/png\*(Aq); .Ve .PP Also, you can use your aliases or file extension names on \f(CW\*(C`content_type\*(C'\fR, like this: .PP .Vb 1 \& send_file(route_parameters\->get(\*(Aqfile\*(Aq), content_type => \*(Aqpng\*(Aq); .Ve .PP The encoding of the file or filehandle may be specified by passing both the \f(CW\*(C`content_type\*(C'\fR and \f(CW\*(C`charset\*(C'\fR options. For example: .PP .Vb 1 \& send_file($fh, content_type => \*(Aqtext/csv\*(Aq, charset => \*(Aqutf\-8\*(Aq ); .Ve .PP For files outside your \fBpublic\fR folder, you can use the \f(CW\*(C`system_path\*(C'\fR switch. Just bear in mind that its use needs caution as it can be dangerous. .PP .Vb 1 \& send_file(\*(Aq/etc/passwd\*(Aq, system_path => 1); .Ve .PP If you have your data in a scalar variable, \f(CW\*(C`send_file\*(C'\fR can be useful as well. Pass a reference to that scalar, and \f(CW\*(C`send_file\*(C'\fR will behave as if there was a file with that contents: .PP .Vb 1 \& send_file( \e$data, content_type => \*(Aqimage/png\*(Aq ); .Ve .PP Note that Dancer is unable to guess the content type from the data contents. Therefore you might need to set the \f(CW\*(C`content_type\*(C'\fR properly. For this kind of usage an attribute named \f(CW\*(C`filename\*(C'\fR can be useful. It is used as the Content-Disposition header, to hint the browser about the filename it should use. .PP .Vb 2 \& send_file( \e$data, content_type => \*(Aqimage/png\*(Aq \& filename => \*(Aqonion.png\*(Aq ); .Ve .PP By default the Content-Disposition header uses the \*(L"attachment\*(R" type, which triggers a \*(L"Save\*(R" dialog in some browsers. Supply a \f(CW\*(C`content_disposition\*(C'\fR attribute of \*(L"inline\*(R" to have the file displayed inline by the browser. .SS "set" .IX Subsection "set" Defines a setting: .PP .Vb 1 \& set something => \*(Aqvalue\*(Aq; .Ve .PP You can set more than one value at once: .PP .Vb 1 \& set something => \*(Aqvalue\*(Aq, otherthing => \*(Aqothervalue\*(Aq; .Ve .SS "setting" .IX Subsection "setting" Returns the value of a given setting: .PP .Vb 1 \& setting(\*(Aqsomething\*(Aq); # \*(Aqvalue\*(Aq .Ve .SS "session" .IX Subsection "session" Provides access to all data stored in the user's session (if any). .PP It can also be used as a setter to store data in the session: .PP .Vb 6 \& # getter example \& get \*(Aq/user\*(Aq => sub { \& if (session(\*(Aquser\*(Aq)) { \& return "Hello, ".session(\*(Aquser\*(Aq)\->name; \& } \& }; \& \& # setter example \& post \*(Aq/user/login\*(Aq => sub { \& ... \& if ($logged_in) { \& session user => $user; \& } \& ... \& }; .Ve .PP You may also need to clear a session: .PP .Vb 6 \& # destroy session \& get \*(Aq/logout\*(Aq => sub { \& ... \& app\->destroy_session; \& ... \& }; .Ve .PP If you need to fetch the session \s-1ID\s0 being used for any reason: .PP .Vb 1 \& my $id = session\->id; .Ve .SS "splat" .IX Subsection "splat" Returns the list of captures made from a route handler with a route pattern which includes wildcards: .PP .Vb 4 \& get \*(Aq/file/*.*\*(Aq => sub { \& my ($file, $extension) = splat; \& ... \& }; .Ve .PP There is also the extensive splat (A.K.A. \*(L"megasplat\*(R"), which allows extensive greedier matching, available using two asterisks. The additional path is broken down and returned as an arrayref: .PP .Vb 4 \& get \*(Aq/entry/*/tags/**\*(Aq => sub { \& my ( $entry_id, $tags ) = splat; \& my @tags = @{$tags}; \& }; .Ve .PP The \f(CW\*(C`splat\*(C'\fR keyword in the above example for the route \fI/entry/1/tags/one/two\fR would set \f(CW$entry_id\fR to \f(CW1\fR and \f(CW$tags\fR to \f(CW\*(C`[\*(Aqone\*(Aq, \*(Aqtwo\*(Aq]\*(C'\fR. .SS "start" .IX Subsection "start" Starts the application or the standalone server (depending on the deployment choices). .PP This keyword should be called at the very end of the script, once all routes are defined. At this point, Dancer2 takes over. .SS "to_app" .IX Subsection "to_app" Returns the \s-1PSGI\s0 coderef for the current (and only the current) application. .PP You can call it as a method on the class or as a \s-1DSL:\s0 .PP .Vb 1 \& my $app = MyApp\->to_app; \& \& # or \& \& my $app = to_app; .Ve .PP There is a Dancer Advent Calendar article covering this keyword and its usage further. .SS "psgi_app" .IX Subsection "psgi_app" Provides the same functionality as \f(CW\*(C`to_app\*(C'\fR but uses the deprecated Dispatcher engine. You should use \f(CW\*(C`to_app\*(C'\fR instead. .SS "status" .IX Subsection "status" Changes the status code provided by an action. By default, an action will produce an \f(CW\*(C`HTTP 200 OK\*(C'\fR status code, meaning everything is \s-1OK:\s0 .PP .Vb 7 \& get \*(Aq/download/:file\*(Aq => { \& if (! \-f route_parameters\->get(\*(Aqfile\*(Aq)) { \& status \*(Aqnot_found\*(Aq; \& return "File does not exist, unable to download"; \& } \& # serving the file... \& }; .Ve .PP In that example, Dancer will notice that the status has changed, and will render the response accordingly. .PP The \f(CW\*(C`status\*(C'\fR keyword receives either a numeric status code or its name in lower case, with underscores as a separator for blanks \- see the list in \&\*(L"\s-1HTTP CODES\*(R"\s0 in Dancer2::Core::HTTP. As an example, The above call translates to setting the code to \f(CW404\fR. .SS "template" .IX Subsection "template" Returns the response of processing the given template with the given parameters (and optional settings), wrapping it in the default or specified layout too, if layouts are in use. .PP An example of a route handler which returns the result of using template to build a response with the current template engine: .PP .Vb 4 \& get \*(Aq/\*(Aq => sub { \& ... \& return template \*(Aqsome_view\*(Aq, { token => \*(Aqvalue\*(Aq}; \& }; .Ve .PP Note that \f(CW\*(C`template\*(C'\fR simply returns the content, so when you use it in a route handler, if execution of the route handler should stop at that point, make sure you use \f(CW\*(C`return\*(C'\fR to ensure your route handler returns the content. .PP Since \f(CW\*(C`template\*(C'\fR just returns the result of rendering the template, you can also use it to perform other templating tasks, e.g. generating emails: .PP .Vb 8 \& post \*(Aq/some/route\*(Aq => sub { \& if (...) { \& email { \& to => \*(Aqsomeone@example.com\*(Aq, \& from => \*(Aqfoo@example.com\*(Aq, \& subject => \*(AqHello there\*(Aq, \& msg => template(\*(Aqemails/foo\*(Aq, { name => body_parameters\->get(\*(Aqname\*(Aq) }), \& }; \& \& return template \*(Aqmessage_sent\*(Aq; \& } else { \& return template \*(Aqerror\*(Aq; \& } \& }; .Ve .PP Compatibility notice: \f(CW\*(C`template\*(C'\fR was changed in version 1.3090 to immediately interrupt execution of a route handler and return the content, as it's typically used at the end of a route handler to return content. However, this caused issues for some people who were using \f(CW\*(C`template\*(C'\fR to generate emails etc, rather than accessing the template engine directly, so this change has been reverted in 1.3091. .PP The first parameter should be a template available in the views directory, the second one (optional) is a hashref of tokens to interpolate, and the third (again optional) is a hashref of options. .PP For example, to disable the layout for a specific request: .PP .Vb 3 \& get \*(Aq/\*(Aq => sub { \& template \*(Aqindex\*(Aq, {}, { layout => undef }; \& }; .Ve .PP Or to request a specific layout, of course: .PP .Vb 3 \& get \*(Aq/user\*(Aq => sub { \& template \*(Aquser\*(Aq, {}, { layout => \*(Aquser\*(Aq }; \& }; .Ve .PP Some tokens are automatically added to your template (\f(CW\*(C`perl_version\*(C'\fR, \&\f(CW\*(C`dancer_version\*(C'\fR, \f(CW\*(C`settings\*(C'\fR, \f(CW\*(C`request\*(C'\fR, \f(CW\*(C`vars\*(C'\fR and, if you have sessions enabled, \f(CW\*(C`session\*(C'\fR). Check Default Template Variables for further details. .SS "to_dumper ($structure)" .IX Subsection "to_dumper ($structure)" Serializes a structure with Data::Dumper. .PP Calling this function will \fBnot\fR trigger the serialization's hooks. .SS "to_json ($structure, \e%options)" .IX Subsection "to_json ($structure, %options)" Serializes a structure to \s-1JSON.\s0 You should probably use \f(CW\*(C`encode_json\*(C'\fR instead which handles encoding the result for you. .SS "to_yaml ($structure)" .IX Subsection "to_yaml ($structure)" Serializes a structure to \s-1YAML.\s0 .PP Calling this function will \fBnot\fR trigger the serialization's hooks. .SS "true" .IX Subsection "true" Constant that returns a true value (1). .SS "upload" .IX Subsection "upload" Provides access to file uploads. Any uploaded file is accessible as a Dancer2::Core::Request::Upload object. You can access all parsed uploads via: .PP .Vb 4 \& post \*(Aq/some/route\*(Aq => sub { \& my $file = upload(\*(Aqfile_input_foo\*(Aq); \& # $file is a Dancer2::Core::Request::Upload object \& }; .Ve .PP If you named multiple inputs of type \*(L"file\*(R" with the same name, the \f(CW\*(C`upload\*(C'\fR keyword would return an Array of Dancer2::Core::Request::Upload objects: .PP .Vb 4 \& post \*(Aq/some/route\*(Aq => sub { \& my ($file1, $file2) = upload(\*(Aqfiles_input\*(Aq); \& # $file1 and $file2 are Dancer2::Core::Request::Upload objects \& }; .Ve .PP You can also access the raw hashref of parsed uploads via the current \&\f(CW\*(C`request\*(C'\fR object: .PP .Vb 5 \& post \*(Aq/some/route\*(Aq => sub { \& my $all_uploads = request\->uploads; \& # $all_uploads\->{\*(Aqfile_input_foo\*(Aq} is a Dancer2::Core::Request::Upload object \& # $all_uploads\->{\*(Aqfiles_input\*(Aq} is an arrayref of Dancer2::Core::Request::Upload objects \& }; .Ve .PP Note that you can also access the filename of the upload received via the \&\f(CW\*(C`body_parameters\*(C'\fR keyword: .PP .Vb 3 \& post \*(Aq/some/route\*(Aq => sub { \& # body_parameters\->get(\*(Aqfiles_input\*(Aq) is the filename of the file uploaded \& }; .Ve .PP See Dancer2::Core::Request::Upload for details about the interface provided. .SS "uri_for" .IX Subsection "uri_for" Returns a fully-qualified \s-1URI\s0 for the given path: .PP .Vb 4 \& get \*(Aq/\*(Aq => sub { \& redirect uri_for(\*(Aq/path\*(Aq); \& # can be something like: http://localhost:5000/path \& }; .Ve .PP Query string parameters can be provided by passing a hashref as a second param: .PP .Vb 2 \& uri_for(\*(Aq/path\*(Aq, { foo => \*(Aqbar\*(Aq }); \& # would return e.g. http://localhost:5000/path?foo=bar .Ve .PP By default, the parameters will be \s-1URL\s0 encoded: .PP .Vb 2 \& uri_for(\*(Aq/path\*(Aq, { foo => \*(Aqhope;faith\*(Aq }); \& # would return http://localhost:5000/path?foo=hope%3Bfaith .Ve .PP If desired (for example, if you've already encoded your query parameters and you want to prevent double encoding) you can disable \&\s-1URL\s0 encoding via a third parameter: .PP .Vb 2 \& uri_for(\*(Aq/path\*(Aq, { foo => \*(Aqqux%3Dquo\*(Aq }, 1); \& # would return http://localhost:5000/path?foo=qux%3Dquo .Ve .SS "captures" .IX Subsection "captures" Returns a reference to a copy of \f(CW\*(C`%+\*(C'\fR, if there are named captures in the route's regular expression. .PP Named captures are a feature of Perl 5.10, and are not supported in earlier versions: .PP .Vb 10 \& get qr{ \& / (? user | ticket | comment ) \& / (? delete | find ) \& / (? \ed+ ) \& /?$ \& }x \& , sub { \& my $value_for = captures; \& "i don\*(Aqt want to $$value_for{action} the $$value_for{object} $$value_for{id} !" \& }; .Ve .SS "var" .IX Subsection "var" Provides an accessor for variables shared between hooks and route handlers. Given a key/value pair, it sets a variable: .PP .Vb 3 \& hook before => sub { \& var foo => 42; \& }; .Ve .PP Later, route handlers and other hooks will be able to read that variable: .PP .Vb 4 \& get \*(Aq/path\*(Aq => sub { \& my $foo = var \*(Aqfoo\*(Aq; \& ... \& }; .Ve .SS "vars" .IX Subsection "vars" Returns the hashref of all shared variables set during the hook/route chain with the \f(CW\*(C`var\*(C'\fR keyword: .PP .Vb 5 \& get \*(Aq/path\*(Aq => sub { \& if (vars\->{foo} eq 42) { \& ... \& } \& }; .Ve .SS "warning" .IX Subsection "warning" Logs a warning message through the current logger engine: .PP .Vb 1 \& warning "This is a warning"; .Ve .PP See Dancer2::Core::Role::Logger for details on how to configure where log messages go. .SH "AUTHOR" .IX Header "AUTHOR" Dancer Core Developers .SH "COPYRIGHT AND LICENSE" .IX Header "COPYRIGHT AND LICENSE" This software is copyright (c) 2021 by Alexis Sukrieh. .PP This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.