.\" Automatically generated by Pod::Man 4.14 (Pod::Simple 3.43) .\" .\" 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 "2023-12-15" "perl v5.36.0" "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 1.1.0 .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 gen \-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. Finally, \fI.dancer\fR indicates the root directory of your app, making it easier for Dancer2 to determine the various paths it needs for finding resources and code within your application. .PP 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 gen \-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 You can also provide routes with a name: .PP .Vb 1 \& get \*(Aqhi_to\*(Aq => \*(Aq/hello/:name\*(Aq => sub {...}; .Ve .PP See \*(L"uri_for_route\*(R" in Dancer2::Manual::Keywords on how this can be used. .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 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_stacktrace\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.) .Sp (In older versions, \fBshow_errors\fR was used instead of \fBshow_stacktrace\fR. Both are supported, but \fBshow_errors\fR is deprecated.) .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_stacktrace\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_stacktrace: 1 .Ve .PP And in a production one: .PP .Vb 4 \& # appdir/environments/production.yml \& log: \*(Aqwarning\*(Aq \& startup_info: 0 \& show_stacktrace: 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 gen \-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 See \*(L"\s-1DSL\s0 Keywords manual\*(R" in Dancer2::Manual::Keywords for a complete list of keywords provided by Dancer2. .SH "AUTHOR" .IX Header "AUTHOR" Dancer Core Developers .SH "COPYRIGHT AND LICENSE" .IX Header "COPYRIGHT AND LICENSE" This software is copyright (c) 2023 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.