.\" Automatically generated by Pod::Man 2.28 (Pod::Simple 3.28) .\" .\" 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 turned on, 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 .\" .\" Accent mark definitions (@(#)ms.acc 1.5 88/02/08 SMI; from UCB 4.2). .\" Fear. Run. Save yourself. No user-serviceable parts. . \" fudge factors for nroff and troff .if n \{\ . ds #H 0 . ds #V .8m . ds #F .3m . ds #[ \f1 . ds #] \fP .\} .if t \{\ . ds #H ((1u-(\\\\n(.fu%2u))*.13m) . ds #V .6m . ds #F 0 . ds #[ \& . ds #] \& .\} . \" simple accents for nroff and troff .if n \{\ . ds ' \& . ds ` \& . ds ^ \& . ds , \& . ds ~ ~ . ds / .\} .if t \{\ . ds ' \\k:\h'-(\\n(.wu*8/10-\*(#H)'\'\h"|\\n:u" . ds ` \\k:\h'-(\\n(.wu*8/10-\*(#H)'\`\h'|\\n:u' . ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'^\h'|\\n:u' . ds , \\k:\h'-(\\n(.wu*8/10)',\h'|\\n:u' . ds ~ \\k:\h'-(\\n(.wu-\*(#H-.1m)'~\h'|\\n:u' . ds / \\k:\h'-(\\n(.wu*8/10-\*(#H)'\z\(sl\h'|\\n:u' .\} . \" troff and (daisy-wheel) nroff accents .ds : \\k:\h'-(\\n(.wu*8/10-\*(#H+.1m+\*(#F)'\v'-\*(#V'\z.\h'.2m+\*(#F'.\h'|\\n:u'\v'\*(#V' .ds 8 \h'\*(#H'\(*b\h'-\*(#H' .ds o \\k:\h'-(\\n(.wu+\w'\(de'u-\*(#H)/2u'\v'-.3n'\*(#[\z\(de\v'.3n'\h'|\\n:u'\*(#] .ds d- \h'\*(#H'\(pd\h'-\w'~'u'\v'-.25m'\f2\(hy\fP\v'.25m'\h'-\*(#H' .ds D- D\\k:\h'-\w'D'u'\v'-.11m'\z\(hy\v'.11m'\h'|\\n:u' .ds th \*(#[\v'.3m'\s+1I\s-1\v'-.3m'\h'-(\w'I'u*2/3)'\s-1o\s+1\*(#] .ds Th \*(#[\s+2I\s-2\h'-\w'I'u*3/5'\v'-.3m'o\v'.3m'\*(#] .ds ae a\h'-(\w'a'u*4/10)'e .ds Ae A\h'-(\w'A'u*4/10)'E . \" corrections for vroff .if v .ds ~ \\k:\h'-(\\n(.wu*9/10-\*(#H)'\s-2\u~\d\s+2\h'|\\n:u' .if v .ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'\v'-.4m'^\v'.4m'\h'|\\n:u' . \" for low resolution devices (crt and lpr) .if \n(.H>23 .if \n(.V>19 \ \{\ . ds : e . ds 8 ss . ds o a . ds d- d\h'-1'\(ga . ds D- D\h'-1'\(hy . ds th \o'bp' . ds Th \o'LP' . ds ae ae . ds Ae AE .\} .rm #[ #] #H #V #F C .\" ======================================================================== .\" .IX Title "Dancer2::Cookbook 3pm" .TH Dancer2::Cookbook 3pm "2014-10-15" "perl v5.20.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::Cookbook \- Example\-driven quick\-start to the Dancer2 web framework .SH "VERSION" .IX Header "VERSION" version 0.152000 .SH "DESCRIPTION" .IX Header "DESCRIPTION" A quick-start guide with examples to get you up and running with the Dancer2 web framework. .SH "BEGINNER'S DANCE" .IX Header "BEGINNER'S DANCE" .SS "A simple Dancer2 web app" .IX Subsection "A simple Dancer2 web app" Dancer2 has been designed to be easy to work with \- it's trivial to write a simple web app, but still has the power to work with larger projects. To start with, let's make an incredibly simple \*(L"Hello World\*(R" example: .PP .Vb 1 \& #!/usr/bin/perl \& \& use Dancer2; \& \& get \*(Aq/hello/:name\*(Aq => sub { \& return "Why, hello there " . params\->{name}; \& }; \& \& dance; .Ve .PP Yes \- the above is a fully-functioning web app; running that script will launch a webserver listening on the default port (3000). Now you can make a request .PP .Vb 2 \& $ curl http://localhost:3000/hello/Bob \& Why, hello there Bob .Ve .PP and it will say hello. The \f(CW\*(C`:name\*(C'\fR part is a named parameter within the route specification, whose value is made available through \f(CW\*(C`params\*(C'\fR. .PP Note that you don't need to use the \f(CW\*(C`strict\*(C'\fR and \f(CW\*(C`warnings\*(C'\fR pragmas; they are already loaded by Dancer2. .SS "Starting a Dancer2 project" .IX Subsection "Starting a Dancer2 project" The above simple example is fine for trivial projects, but for anything more complex, you'll want a more maintainable solution \- enter the \f(CW\*(C`dancer2\*(C'\fR helper script, which will build the framework of your application with a single command: .PP .Vb 10 \& $ dancer2 \-a mywebapp \& + mywebapp \& + mywebapp/bin \& + mywebapp/bin/app.pl \& + mywebapp/config.yml \& + mywebapp/environments \& + mywebapp/environments/development.yml \& + mywebapp/environments/production.yml \& + mywebapp/views \& + mywebapp/views/index.tt \& + mywebapp/views/layouts \& + mywebapp/views/layouts/main.tt \& + mywebapp/MANIFEST.SKIP \& + mywebapp/lib \& + mywebapp/lib/ \& + mywebapp/lib/mywebapp.pm \& + mywebapp/public \& + mywebapp/public/css \& + mywebapp/public/css/style.css \& + mywebapp/public/css/error.css \& + mywebapp/public/images \& + mywebapp/public/500.html \& + mywebapp/public/404.html \& + mywebapp/public/dispatch.fcgi \& + mywebapp/public/dispatch.cgi \& + mywebapp/public/javascripts \& + mywebapp/public/javascripts/jquery.js \& + mywebapp/t \& + mywebapp/t/002_index_route.t \& + mywebapp/t/001_base.t \& + mywebapp/Makefile.PL .Ve .PP As you can see, it creates a directory named after the name of the app, along with a configuration file, a views directory (where your templates and layouts will live), an environments directory (where environment-specific settings live), a module containing the actual guts of your application and a script to start it \- or to run your web app via Plack/PSGI. .SH "DANCE ROUTINES: ROUTES" .IX Header "DANCE ROUTINES: ROUTES" .SS "Declaring routes" .IX Subsection "Declaring routes" 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 " . params\->{name}; \& }; .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. .SS "Handling multiple \s-1HTTP\s0 request methods" .IX Subsection "Handling multiple HTTP request methods" 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 "Retrieving request parameters" .IX Subsection "Retrieving request parameters" The params keyword returns a hashref of request parameters; these will be parameters supplied on the query string within the path itself (with named placeholders) and, for \s-1HTTTP POST\s0 requests, the content of the \s-1POST\s0 body. .SS "Named parameters in route path declarations" .IX Subsection "Named parameters in route path declarations" As seen above, you can use \f(CW\*(C`:somename\*(C'\fR in a route's path to capture part of the path; this will become available by calling params. .PP So, for a web app where you want to display information on a company, you might use something like: .PP .Vb 4 \& get \*(Aq/company/view/:companyid\*(Aq => sub { \& my $company_id = params\->{companyid}; \& # Look up the company and return appropriate page \& }; .Ve .SS "Wildcard path matching and splat" .IX Subsection "Wildcard path matching and splat" You can also declare wildcards in a path and retrieve the values they matched with the splat keyword: .PP .Vb 11 \& get \*(Aq/*/*\*(Aq => sub { \& my ($action, $id) = splat; \& if (my $action eq \*(Aqview\*(Aq) { \& return display_item($id); \& } elsif ($action eq \*(Aqdelete\*(Aq) { \& return delete_item($id); \& } else { \& status \*(Aqnot_found\*(Aq; \& return "What?"; \& } \& }; .Ve .SS "Before filters \- processed before a request" .IX Subsection "Before filters - processed before a request" A before filter declares code which should be handled before a request is passed to the appropriate route. .PP .Vb 3 \& hook before => sub { \& forward \*(Aq/foo/oversee\*(Aq, { note => \*(AqHi there\*(Aq }; \& }; \& \& get \*(Aq/foo/*\*(Aq => sub { \& my ($match) = splat; # \*(Aqoversee\*(Aq; \& params\->{note}; # \*(AqHi there\*(Aq \& }; .Ve .PP The above declares a before filter which uses \f(CW\*(C`forward\*(C'\fR to do an internal redirect to \f(CW\*(C`/foo/oversee\*(C'\fR with an additional parameter \f(CW\*(C`note\*(C'\fR. .PP See also the hook keyword. .SS "Default route" .IX Subsection "Default route" In case you want to avoid a \fI404 error\fR, or handle multiple routes in the same way and you don't feel like configuring all of them, you can set up a default route handler. .PP The default route handler will handle any request that doesn't get served by any other route. .PP All you need to do is set up the following route as the \fBlast\fR route: .PP .Vb 4 \& any qr{.*} => sub { \& status \*(Aqnot_found\*(Aq; \& template \*(Aqspecial_404\*(Aq, { path => request\->path }; \& }; .Ve .PP Then you can set up the template like so: .PP .Vb 1 \& You tried to reach [% path %], but it is unavailable at the moment. \& \& Please try again or contact us at . .Ve .ie n .SS "Using the ""auto_page"" feature for automatic route creation" .el .SS "Using the \f(CWauto_page\fP feature for automatic route creation" .IX Subsection "Using the auto_page feature for automatic route creation" For simple \*(L"static\*(R" pages you can simply enable the \f(CW\*(C`auto_page\*(C'\fR config setting; this means you don't need to declare a route handler for those pages; if a request is for \f(CW\*(C`/foo/bar\*(C'\fR, Dancer2 will check for a matching view (e.g. \f(CW\*(C`/foo/bar.tt\*(C'\fR and render it with the default layout etc. if found. For full details, see the documentation for the auto_page setting. .SS "Simplifying Ajax queries with the Ajax plugin" .IX Subsection "Simplifying Ajax queries with the Ajax plugin" As an Ajax query is just an \s-1HTTP\s0 query, it's similar to a \s-1GET\s0 or \s-1POST\s0 route. You may ask yourself why you may want to use the \f(CW\*(C`ajax\*(C'\fR keyword (from the Dancer2::Plugin::Ajax plugin) instead of a simple \f(CW\*(C`get\*(C'\fR. .PP Let's say you have a path like \f(CW\*(C`/user/:user\*(C'\fR in your application. You may want to be able to serve this page with a layout and \s-1HTML\s0 content. But you may also want to be able to call this same url from a javascript query using Ajax. .PP So, instead of having the following code: .PP .Vb 10 \& get \*(Aq/user/:user\*(Aq => sub { \& if (request\->is_ajax) { \& # create xml, set headers to text/xml, blablabla \& header(\*(AqContent\-Type\*(Aq => \*(Aqtext/xml\*(Aq); \& header(\*(AqCache\-Control\*(Aq => \*(Aqno\-store, no\-cache, must\-revalidate\*(Aq); \& to_xml({...}) \& }else{ \& template users, {....} \& } \& }; .Ve .PP you can have .PP .Vb 3 \& get \*(Aq/user/:user\*(Aq => sub { \& template users, {...} \& } .Ve .PP and .PP .Vb 3 \& ajax \*(Aq/user/:user\*(Aq => sub { \& to_xml({...}, RootName => undef); \& } .Ve .PP Because it's an Ajax query, you know you need to return \s-1XML\s0 content, so the content type of the response is set for you. .SS "Using the prefix feature to split your application" .IX Subsection "Using the prefix feature to split your application" For better maintainability, you may want to separate some of your application components into different packages. Let's say we have a simple web app with an admin section and want to maintain this in a different package: .PP .Vb 3 \& package myapp; \& use Dancer2; \& use myapp::admin; \& \& prefix undef; \& \& get \*(Aq/\*(Aq => sub {...}; \& \& 1; \& \& package myapp::admin; \& use Dancer2 appname => \*(Aqmyapp\*(Aq; \& \& prefix \*(Aq/admin\*(Aq; \& \& get \*(Aq/\*(Aq => sub {...}; \& \& 1; .Ve .PP The following routes will be generated for us: .PP .Vb 4 \& \- get / \& \- get /admin/ \& \- head / \& \- head /admin/ .Ve .PP By default, a separate application is created for every package that uses Dancer2. The \f(CW\*(C`appname\*(C'\fR tag is used to collect routes and hooks into a single Dancer2 application. In the above example, \f(CW\*(C`appname => \*(Aqmyapp\*(Aq\*(C'\fR adds the routes from \f(CW\*(C`myapp::admin\*(C'\fR to the routes of the app \f(CW\*(C`myapp\*(C'\fR. .PP When using multiple applications please ensure that your path definitions do not overlap. For example, if using a default route as described above, once a request is matched to the default route then no further routes (or applications) would be reached. .SH "MUSCLE MEMORY: STORING DATA" .IX Header "MUSCLE MEMORY: STORING DATA" .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 To make use of sessions, you must first enable the session engine \- pick the session engine you want to use, then declare it in your config file like this: .PP .Vb 1 \& session: Simple .Ve .PP The Dancer2::Session::Simple backend implements very simple in-memory session storage. This will be fast and useful for testing, but such sessions will not persist between restarts of your app. .PP You can also use the Dancer2::Session::YAML backend included with Dancer2, which stores session data on disc in \s-1YAML\s0 files (since \s-1YAML\s0 is a nice human-readable format, it makes inspecting the contents of sessions a breeze): .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 \&'\s-1YAML\s0' in the example is the session backend to use; this is shorthand for Dancer2::Session::YAML. There are other session backends \- for instance Dancer2::Session::Memcached \- but the \s-1YAML\s0 backend is simple and easy to 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, Dancer2::Session::Storable etc., 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 \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" \&\fBNote!\fR The following example will in this form prevent the application from returning static content (files inside the \f(CW\*(C`public/\*(C'\fR directory, like \s-1CSS,\s0 javascript files etc.) when the user is not logged in, because the before hook is executed on the static files as well. A simple way to prevent this is using Plack::Middleware::Static for serving static files. An example can be found here. .PP 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 with a before filter to check their session: .PP .Vb 2 \& use Dancer2; \& set session => "Simple"; \& \& hook before => sub { \& if (!session(\*(Aquser\*(Aq) && request\->dispatch_path !~ m{^/login}) { \& forward \*(Aq/login\*(Aq, { requested_path => request\->dispatch_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 \& # param(\*(Aqrequested_path\*(Aq), so could be put in a hidden field in the form \& template \*(Aqlogin\*(Aq, { path => param(\*(Aqrequested_path\*(Aq) }; \& }; \& \& post \*(Aq/login\*(Aq => sub { \& # Validate the username and password they supplied \& if (param(\*(Aquser\*(Aq) eq \*(Aqbob\*(Aq && param(\*(Aqpass\*(Aq) eq \*(Aqletmein\*(Aq) { \& session user => param(\*(Aquser\*(Aq); \& redirect param(\*(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: \& \& \& \& \& \&
\& \& .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 10 \& post \*(Aq/login\*(Aq => sub { \& my $user = database\->quick_select(\*(Aqusers\*(Aq, \& { username => params\->{user} } \& ); \& if (!$user) { \& warning "Failed login for unrecognised user " . params\->{user}; \& redirect \*(Aq/login?failed=1\*(Aq; \& } else { \& if (Crypt::SaltedHash\->validate($user\->{password}, params\->{pass})) \& { \& debug "Password correct"; \& # Logged in successfully \& session user => $user; \& redirect params\->{path} || \*(Aq/\*(Aq; \& } else { \& debug("Login failed \- password incorrect for " . params\->{user}); \& 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 .SH "APPEARANCE: TEMPLATES AND LAYOUTS" .IX Header "APPEARANCE: TEMPLATES AND LAYOUTS" Returning plain content is all well and good for examples or trivial apps, but soon you'll want to use templates to maintain separation between your code and your content. Dancer2 makes this easy. .PP Your route handlers can use the template keyword to render templates. .SS "Views" .IX Subsection "Views" It's possible to render the action's content with a template, this is called a view. The \f(CW\*(C`appdir/views\*(C'\fR directory is the place where views are located. .PP You can change this location by changing the setting 'views'. .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 import the Template module in your application code. .PP Views use a \f(CW\*(C`.tt\*(C'\fR extension by convention. This can be overridden by setting the \f(CW\*(C`extension\*(C'\fR attribute in the template engine configuration. See the Using Templates section in the manual for details. .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 = params\->{name}; \& 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). .SS "Layouts" .IX Subsection "Layouts" A layout is a special view, located in the 'layouts' 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 to avoid lots of needless duplication of \s-1HTML :\s0) .PP Here is an example of a layout: \f(CW\*(C`views/layouts/main.tt\*(C'\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\*(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 "Templates and unicode" .IX Subsection "Templates and unicode" 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 "Template Toolkit's \s-1WRAPPER\s0 directive in Dancer2" .IX Subsection "Template Toolkit's WRAPPER directive in Dancer2" Dancer2 already provides a WRAPPER-like ability, which we call a \*(L"layout\*(R". The reason we don't use Template Toolkit's \s-1WRAPPER \s0(which also makes us incompatible with it) is because not all template systems support it. Actually, most don't. .PP However, you might want to use it, and be able to define \s-1META\s0 variables and regular Template::Toolkit variables. .PP These few steps will get you there: .IP "\(bu" 4 Disable the layout in Dancer2 .Sp You can do this by simply commenting (or removing) the \f(CW\*(C`layout\*(C'\fR configuration in the config file. .IP "\(bu" 4 Use the Template Toolkit template engine .Sp Change the configuration of the template to Template Toolkit: .Sp .Vb 2 \& # in config.yml \& template: "template_toolkit" .Ve .IP "\(bu" 4 Tell the Template Toolkit engine which wrapper to use .Sp .Vb 6 \& # in config.yml \& # ... \& engines: \& template: \& template_toolkit: \& WRAPPER: layouts/main.tt .Ve .PP Done! Everything will work fine out of the box, including variables and \s-1META\s0 variables. .SH "SETTING THE STAGE: CONFIGURATION AND LOGGING" .IX Header "SETTING THE STAGE: CONFIGURATION AND LOGGING" .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 \f(CW\*(C`config.yml\*(C'\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 Note that you can change the running environment using the \f(CW\*(C`\-\-environment\*(C'\fR command line switch. .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 .SS "Accessing configuration information" .IX Subsection "Accessing configuration information" \fIFrom inside your application\fR .IX Subsection "From inside your application" .PP 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 :) .PP \fIFrom a separate script\fR .IX Subsection "From a separate script" .PP You may want to access your webapp's configuration from outside your webapp. You could, of course, use the \s-1YAML\s0 module of your choice and load your webapps's \f(CW\*(C`config.yml\*(C'\fR, but chances are that this is not convenient. .PP Use Dancer2 instead. You can simply use the values from \f(CW\*(C`config.yml\*(C'\fR and some additional default values: .PP .Vb 4 \& # bin/show_app_config.pl \& use Dancer2; \& print "template:".config\->{template}."\en"; # simple \& print "log:".config\->{log}."\en"; # undef .Ve .PP Note that \f(CW\*(C`config\->{log}\*(C'\fR should result in an \f(CW\*(C`undef\*(C'\fR error on a default scaffold since the environment isn't loaded and log is defined in the environment and not in \f(CW\*(C`config.yml\*(C'\fR. Hence \f(CW\*(C`undef\*(C'\fR. .PP If you want to load an environment you need to tell Dancer2 where to look for it. One way to do so is to tell Dancer2 where the webapp lives. From there Dancer2 deduces where the config.yml file is (typically \&\f(CW\*(C`$webapp/config.yml\*(C'\fR). .PP .Vb 4 \& # bin/show_app_config_and_env.pl \& use FindBin; \& use Cwd qw/realpath/; \& use Dancer2; \& \& # tell the Dancer2 where the app lives \& my $appdir = realpath( "$FindBin::Bin/.."); \& \& Dancer2::Config::setting(\*(Aqappdir\*(Aq, $appdir); \& Dancer2::Config::load(); \& \& # getter \& print "environment:".config\->{environment}."\en"; # development \& print "log:".config\->{log}."\en"; # value from development environment .Ve .PP By default Dancer2 loads the development environment (typically \&\f(CW\*(C`$webapp/environment/development.yml\*(C'\fR). In contrast to the example above, now you do have a value from the development environment (\f(CW\*(C`environment/development.yml\*(C'\fR). Also note that in the above example Cwd and FindBin are used. They are likely to be already loaded by Dancer2 anyways, so it's not a big overhead. You could just as well hand over a simple path for the app if you like that better, e.g.: .PP .Vb 1 \& Dancer2::Config::setting(\*(Aqappdir\*(Aq,\*(Aq/path/to/app/dir\*(Aq); .Ve .PP If you want to load an environment other than the default, try this: .PP .Vb 2 \& # bin/show_app_config_and_env.pl \& use Dancer2; \& \& # tell the Dancer2 where the app lives \& Dancer2::Config::setting(\*(Aqappdir\*(Aq, \*(Aq/path/to/app/dir\*(Aq); \& \& # which environment to load \& config\->{environment} = \*(Aqproduction\*(Aq; \& \& Dancer2::Config::load(); \& \& # getter \& print "log:".config\->{log}."\en"; # has value from production environment .Ve .PP By the way, you not only get values, you can also set values straightforwardly like we do above with \f(CW\*(C`config\->{environment}=\*(Aqproduction\*(Aq\*(C'\fR. Of course, this value does not get written in any file; it only lives in memory and thus your webapp doesn't have access to it, but you can use it inside your script. .SS "Logging" .IX Subsection "Logging" \fIConfiguring logging\fR .IX Subsection "Configuring logging" .PP 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, 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). .PP \fILogging your own messages\fR .IX Subsection "Logging your own messages" .PP Just call debug, info, warning or error with your message: .PP .Vb 1 \& debug "This is a debug message from my app."; .Ve .SH "RESTING" .IX Header "RESTING" .SS "Writing a \s-1REST\s0 application" .IX Subsection "Writing a REST application" With Dancer2, it's easy to write \s-1REST\s0 applications. Dancer2 provides helpers to serialize and deserialize for the following data formats: .IP "\s-1JSON\s0" 4 .IX Item "JSON" .PD 0 .IP "\s-1YAML\s0" 4 .IX Item "YAML" .IP "\s-1XML\s0" 4 .IX Item "XML" .IP "Data::Dumper" 4 .IX Item "Data::Dumper" .PD .PP To activate this feature, you only have to set the \f(CW\*(C`serializer\*(C'\fR setting to the format you require, for instance in your config file: .PP .Vb 1 \& serializer: JSON .Ve .PP Or directly in your code: .PP .Vb 1 \& set serializer => \*(AqJSON\*(Aq; .Ve .PP From now, all hashrefs or arrayrefs returned by a route will be serialized to the format you chose, and all data received from \fB\s-1POST\s0\fR or \fB\s-1PUT\s0\fR requests will be automatically deserialized. .PP .Vb 5 \& get \*(Aq/hello/:name\*(Aq => sub { \& # this structure will be returned to the client as \& # {"name":"$name"} \& return {name => params\->{name}}; \& }; .Ve .PP It's possible to let the client choose which serializer to use. For this, use the \f(CW\*(C`mutable\*(C'\fR serializer, and an appropriate serializer will be chosen from the \f(CW\*(C`Content\-Type\*(C'\fR header. .PP It's also possible to return a custom error using the send_error keyword. When you don't use a serializer, the \f(CW\*(C`send_error\*(C'\fR function will take a string as first parameter (the message), and an optional \s-1HTTP\s0 code. When using a serializer, the message can be a string, an arrayref or a hashref: .PP .Vb 7 \& get \*(Aq/hello/:name\*(Aq => sub { \& if (...) { \& send_error("you can\*(Aqt do that"); \& # or \& send_error({reason => \*(Aqaccess denied\*(Aq, message => "no"}); \& } \& }; .Ve .PP The content of the error will be serialized using the appropriate serializer. .SH "DANCER ON THE STAGE: DEPLOYMENT" .IX Header "DANCER ON THE STAGE: DEPLOYMENT" .SS "Running stand-alone" .IX Subsection "Running stand-alone" At the simplest, your Dancer2 app can run standalone, operating as its own webserver using HTTP::Server::PSGI. .PP Simply fire up your app: .PP .Vb 3 \& $ perl bin/app.pl \& >> Listening on 0.0.0.0:3000 \& == Entering the dance floor ... .Ve .PP Point your browser at it, and away you go! .PP This option can be useful for small personal web apps or internal apps, but if you want to make your app available to the world, it probably won't suit you. .SS "Auto Reloading with Plack and Shotgun" .IX Subsection "Auto Reloading with Plack and Shotgun" To edit your files without the need to restart the webserver on each file change, simply start your Dancer2 app using plackup and Plack::Loader::Shotgun: .PP .Vb 2 \& $ plackup \-L Shotgun bin/app.pl \& HTTP::Server::PSGI: Accepting connections at http://0:5000/ .Ve .PP Point your browser at it. Files can now be changed in your favorite editor and the browser needs to be refreshed to see the saved changes. .PP Please note that this is not recommended for production for performance reasons. This is the Dancer2 replacement solution of the old Dancer experimental \f(CW\*(C`auto_reload\*(C'\fR option. .PP On Windows, Shotgun loader is known to cause huge memory leaks in a fork-emulation layer. If you are aware of this and still want to run the loader, please use the following command: .PP .Vb 2 \& > set PLACK_SHOTGUN_MEMORY_LEAK=1 && plackup \-L Shotgun bin\eapp.pl \& HTTP::Server::PSGI: Accepting connections at http://0:5000/ .Ve .SS "\s-1CGI\s0 and Fast-CGI" .IX Subsection "CGI and Fast-CGI" In providing ultimate flexibility in terms of deployment, your Dancer2 app can be run as a simple cgi-script out-of-the-box. No additional web-server configuration needed. Your web server should recognize .cgi files and be able to serve Perl scripts. The Perl module Plack::Runner is required. .PP \fIRunning on Apache (\s-1CGI\s0 and \s-1FCGI\s0)\fR .IX Subsection "Running on Apache (CGI and FCGI)" .PP Start by adding the following to your apache configuration (\f(CW\*(C`httpd.conf\*(C'\fR or \&\f(CW\*(C`sites\-available/*site*\*(C'\fR): .PP .Vb 4 \& \& ServerName www.example.com \& DocumentRoot /srv/www.example.com/public \& ServerAdmin you@example.com \& \& \& AllowOverride None \& Options +ExecCGI \-MultiViews +SymLinksIfOwnerMatch \& Order allow,deny \& Allow from all \& AddHandler cgi\-script .cgi \& \& \& RewriteEngine On \& RewriteCond %{REQUEST_FILENAME} !\-f \& RewriteRule ^(.*)$ /dispatch.cgi$1 [QSA,L] \& \& ErrorLog /var/log/apache2/www.example.com\-error.log \& CustomLog /var/log/apache2/www.example.com\-access_log common \& .Ve .PP Note that when using fast-cgi your rewrite rule should be: .PP .Vb 1 \& RewriteRule ^(.*)$ /dispatch.fcgi$1 [QSA,L] .Ve .PP Here, the mod_rewrite magic for Pretty-URLs is directly put in Apache's configuration. But if your web server supports \f(CW\*(C`.htaccess\*(C'\fR files, you can drop those lines in a \f(CW\*(C`.htaccess\*(C'\fR file. .PP To check if your server supports mod_rewrite type \f(CW\*(C`apache2 \-l\*(C'\fR to list modules. To enable \f(CW\*(C`mod_rewrite\*(C'\fR on Debian or Ubuntu, run \f(CW\*(C`a2enmod rewrite\*(C'\fR. Place following code in a file called \f(CW\*(C`.htaccess\*(C'\fR in your application's root folder: .PP .Vb 6 \& # BEGIN dancer application htaccess \& RewriteEngine On \& RewriteCond %{SCRIPT_FILENAME} !\-d \& RewriteCond %{SCRIPT_FILENAME} !\-f \& RewriteRule (.*) /dispatch.cgi$1 [L] \& # END dancer application htaccess .Ve .PP Now you can access your Dancer2 application URLs as if you were using the embedded web server: .PP .Vb 1 \& http://localhost/ .Ve .PP This option is a no-brainer, easy to setup, low maintenance but serves requests slower than all other options. .PP You can use the same technique to deploy with FastCGI, by just changing the line: .PP .Vb 1 \& AddHandler cgi\-script .cgi .Ve .PP to: .PP .Vb 1 \& AddHandler fastcgi\-script .fcgi .Ve .PP Of course remember to update your rewrite rules, if you have set any: .PP .Vb 1 \& RewriteRule (.*) /dispatch.fcgi$1 [L] .Ve .PP Running under an appdir .IX Subsection "Running under an appdir" .PP If you want to deploy multiple applications under the same \f(CW\*(C`VirtualHost\*(C'\fR (using one application per directory, for example) you can use the following example Apache configuration. .PP This example uses the FastCGI dispatcher that comes with Dancer2, but you should be able to adapt this to use any other way of deployment described in this guide. The only purpose of this example is to show how to deploy multiple applications under the same base directory/\f(CW\*(C`VirtualHost\*(C'\fR. .PP .Vb 5 \& \& ServerName localhost \& DocumentRoot "/path/to/rootdir" \& RewriteEngine On \& RewriteCond %{REQUEST_FILENAME} !\-f \& \& \& AllowOverride None \& Options +ExecCGI \-MultiViews +SymLinksIfOwnerMatch \& Order allow,deny \& Allow from all \& AddHandler fastcgi\-script .fcgi \& \& \& RewriteRule /App1(.*)$ /App1/public/dispatch.fcgi$1 [QSA,L] \& RewriteRule /App2(.*)$ /App2/public/dispatch.fcgi$1 [QSA,L] \& ... \& RewriteRule /AppN(.*)$ /AppN/public/dispatch.fcgi$1 [QSA,L] \& .Ve .PP Of course, if your Apache configuration allows that, you can put the RewriteRules in a .htaccess file directly within the application's directory, which lets you add a new application without changing the Apache configuration. .PP \fIRunning on lighttpd (\s-1CGI\s0)\fR .IX Subsection "Running on lighttpd (CGI)" .PP To run as a \s-1CGI\s0 app on lighttpd, just create a soft link to the \f(CW\*(C`dispatch.cgi\*(C'\fR script (created when you run \f(CW\*(C`dancer \-a MyApp\*(C'\fR) inside your system's \f(CW\*(C`cgi\-bin\*(C'\fR folder. Make sure \f(CW\*(C`mod_cgi\*(C'\fR is enabled. .PP .Vb 1 \& ln \-s /path/to/MyApp/public/dispatch.cgi /usr/lib/cgi\-bin/mycoolapp.cgi .Ve .PP \fIRunning on lighttpd (FastCGI)\fR .IX Subsection "Running on lighttpd (FastCGI)" .PP Make sure \f(CW\*(C`mod_fcgi\*(C'\fR is enabled. You also must have \s-1FCGI\s0 installed. .PP This example configuration uses \s-1TCP/IP:\s0 .PP .Vb 11 \& $HTTP["url"] == "^/app" { \& fastcgi.server += ( \& "/app" => ( \& "" => ( \& "host" => "127.0.0.1", \& "port" => "5000", \& "check\-local" => "disable", \& ) \& ) \& ) \& } .Ve .PP Launch your application: .PP .Vb 1 \& plackup \-s FCGI \-\-port 5000 bin/app.pl .Ve .PP This example configuration uses a socket: .PP .Vb 10 \& $HTTP["url"] =~ "^/app" { \& fastcgi.server += ( \& "/app" => ( \& "" => ( \& "socket" => "/tmp/fcgi.sock", \& "check\-local" => "disable", \& ) \& ) \& ) \& } .Ve .PP Launch your application: .PP .Vb 1 \& plackup \-s FCGI \-\-listen /tmp/fcgi.sock bin/app.pl .Ve .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 4 \& # in app.psgi or any other handler \& use Dancer2; \& use MyWebApp; \& use Plack::Builder; \& \& builder { \& enable \*(AqDeflater\*(Aq; \& enable \*(AqSession\*(Aq, store => \*(AqFile\*(Aq; \& enable \*(AqDebug\*(Aq, panels => [ qw ]; \& dance; \& }; .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 4 \& # in your app.psgi or any other handler \& use Dancer2; \& use MyWebApp; \& use Plack::Builder; \& \& my $special_handler = sub { ... }; \& \& builder { \& mount \*(Aq/\*(Aq => dance; \& mount \*(Aq/special\*(Aq => $special_handler; \& }; .Ve .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 "Starman " 4 .IX Item "Starman " \&\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 "Twiggy " 4 .IX Item "Twiggy " \&\f(CW\*(C`Twiggy\*(C'\fR is an \f(CW\*(C`AnyEvent\*(C'\fR web server, it's light and fast. .IP "Corona " 4 .IX Item "Corona " \&\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.pl \& $ plackup \-E deployment \-s Starman \-\-workers=10 \-p 5001 \-a bin/app.pl .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 MyWebApp; \& use Plack::Builder; \& \& builder { \& enable \*(AqDeflater\*(Aq; \& dance; \& }; .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\->psgi_app; \& mount \*(Aq/forum\*(Aq => OurForum\->psgi_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.pl \& \& \& 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 .PP \fIServing static files using Plack::Middleware::Static\fR .IX Subsection "Serving static files using Plack::Middleware::Static" .PP You can use Plack::Middleware::Static to serve your static files instead of Dancer2::Handler::File. That way before hooks will not be executed for them. This is required to make the example in Sessions and logging-in work. .PP First, we have to disable Dancer2::Handler::File in the config: .PP .Vb 1 \& route_handlers: [] .Ve .PP Next, our \f(CW\*(C`bin/app.pl\*(C'\fR should look similar to this: .PP .Vb 4 \& #!/usr/bin/env perl \& use Plack::Builder; \& use Dancer2::FileUtils qw[ path ]; \& use MyApp; \& \& builder { \& enable "Plack::Middleware::Static", \& path => sub { \-f path(\*(Aqpublic\*(Aq, shift) }, \& root => \*(Aqpublic\*(Aq; \& dance; \& }; .Ve .PP The \f(CW\*(C`path\*(C'\fR option returns true if the requested file exists inside the \f(CW\*(C`public/\*(C'\fR directory. For example the file \f(CW\*(C`/css/default.css\*(C'\fR is searched for at \&\f(CW\*(C`public/css/default.css\*(C'\fR. When the file is found, Plack::Middleware::Static returns the requested file from the 'root' directory, which is in this example the \f(CW\*(C`public/\*(C'\fR folder. .SS "Creating a service" .IX Subsection "Creating a service" You can turn your app into a proper service running in the background using one of the following examples. .PP \fIUsing Ubic\fR .IX Subsection "Using Ubic" .PP Ubic is an extensible perlish service manager. You can use it to start and stop any services, automatically start them on reboots or daemon failures, and implement custom status checks. .PP A basic \s-1PSGI\s0 service description (usually in \f(CW\*(C`/etc/ubic/service/application\*(C'\fR): .PP .Vb 1 \& use parent qw(Ubic::Service::Plack); \& \& # if your application is not installed in @INC path: \& sub start { \& my $self = shift; \& $ENV{PERL5LIB} = \*(Aq/path/to/your/application/lib\*(Aq; \& $self\->SUPER::start(@_); \& } \& \& _\|_PACKAGE_\|_\->new( \& server => \*(AqStarman\*(Aq, \& app => \*(Aq/path/to/your/application/app.pl\*(Aq, \& port => 5000, \& user => \*(Aqwww\-data\*(Aq, \& ); .Ve .PP Run \f(CW\*(C`ubic start application\*(C'\fR to start the service. .PP \fIUsing daemontools\fR .IX Subsection "Using daemontools" .PP daemontools is a collection of tools for managing \s-1UNIX\s0 services. You can use it to easily start/restart/stop services. .PP A basic script to start an application: (in \f(CW\*(C`/service/application/run\*(C'\fR) .PP .Vb 1 \& #!/bin/sh \& \& # if your application is not installed in @INC path: \& export PERL5LIB=\*(Aq/path/to/your/application/lib\*(Aq \& \& exec 2>&1 \e \& /usr/local/bin/plackup \-s Starman \-a /path/to/your/application/app.pl \-p 5000 .Ve .SS "Running stand-alone behind a proxy / load balancer" .IX Subsection "Running stand-alone behind a proxy / load balancer" Another option would be to run your app stand-alone as described above, but then use a proxy or load balancer to accept incoming requests (on the standard port 80, say) and feed them to your Dancer2 app. .PP This could be achieved using various software; examples would include: .PP \fIUsing Apache's \f(CI\*(C`mod_proxy\*(C'\fI\fR .IX Subsection "Using Apache's mod_proxy" .PP You could set up a \f(CW\*(C`VirtualHost\*(C'\fR for your web app, and proxy all requests through to it: .PP .Vb 4 \& \& ProxyPass / http://localhost:3000/ \& ProxyPassReverse / http://localhost:3000/ \& .Ve .PP Or, if you want your webapp to share an existing VirtualHost, you could have it under a specified dir: .PP .Vb 2 \& ProxyPass /mywebapp/ http://localhost:3000/ \& ProxyPassReverse /mywebapp/ http://localhost:3000/ .Ve .PP It is important for you to note that the Apache2 modules \f(CW\*(C`mod_proxy\*(C'\fR and \&\f(CW\*(C`mod_proxy_http\*(C'\fR must be enabled: .PP .Vb 2 \& $ a2enmod proxy \& $ a2enmod proxy_http .Ve .PP It is also important to set permissions for proxying for security purposes, below is an example. .PP .Vb 4 \& \& Order allow,deny \& Allow from all \& .Ve .PP \fIUsing perlbal\fR .IX Subsection "Using perlbal" .PP \&\f(CW\*(C`perlbal\*(C'\fR is a single-threaded event-based server written in Perl supporting \s-1HTTP\s0 load balancing, web serving, and a mix of the two, available from . .PP It processes hundreds of millions of requests a day just for LiveJournal, Vox and TypePad and dozens of other \*(L"Web 2.0\*(R" applications. .PP It can also provide a management interface to let you see various information on requests handled etc. .PP It could easily be used to handle requests for your Dancer2 apps, too. .PP It can be easily installed from \s-1CPAN:\s0 .PP .Vb 1 \& perl \-MCPAN \-e \*(Aqinstall Perlbal\*(Aq .Ve .PP Once installed, you'll need to write a configuration file. See the examples provided with perlbal, but you'll probably want something like: .PP .Vb 5 \& CREATE POOL my_dancers \& POOL my_dancers ADD 10.0.0.10:3030 \& POOL my_dancers ADD 10.0.0.11:3030 \& POOL my_dancers ADD 10.0.0.12:3030 \& POOL my_dancers ADD 10.0.0.13:3030 \& \& CREATE SERVICE my_webapp \& SET listen = 0.0.0.0:80 \& SET role = reverse_proxy \& SET pool = my_dancers \& SET persist_client = on \& SET persist_backend = on \& SET verify_backend = on \& ENABLE my_webapp .Ve .PP \fIUsing balance\fR .IX Subsection "Using balance" .PP \&\f(CW\*(C`balance\*(C'\fR is a simple load-balancer from Inlab Software, available from . .PP It could be used simply to hand requests to a standalone Dancer2 app. You could even run several instances of your Dancer2 app, on the same machine or on several machines, and use a machine running \f(CW\*(C`balance\*(C'\fR to distribute the requests between them, for some serious heavy traffic handling! .PP To listen on port 80, and send requests to a Dancer2 app on port 3000: .PP .Vb 1 \& balance http localhost:3000 .Ve .PP To listen on a specified \s-1IP\s0 only on port 80, and distribute requests between multiple Dancer2 apps on multiple other machines: .PP .Vb 1 \& balance \-b 10.0.0.1 80 10.0.0.2:3000 10.0.0.3:3000 10.0.0.4:3000 .Ve .PP \fIUsing lighttpd\fR .IX Subsection "Using lighttpd" .PP You can use lighttp's \f(CW\*(C`mod_proxy\*(C'\fR: .PP .Vb 7 \& $HTTP["url"] =~ "/application" { \& proxy.server = ( \& "/" => ( \& "application" => ( "host" => "127.0.0.1", "port" => 3000 ) \& ) \& ) \& } .Ve .PP This configuration will proxy all requests to the \f(CW\*(C`/application\*(C'\fR path to the path \f(CW\*(C`/\*(C'\fR on localhost:3000. .PP \fIUsing Nginx\fR .IX Subsection "Using Nginx" .PP with Nginx: .PP .Vb 3 \& upstream backendurl { \& server unix:THE_PATH_OF_YOUR_PLACKUP_SOCKET_HERE.sock; \& } \& \& server { \& listen 80; \& server_name YOUR_HOST_HERE; \& \& access_log /var/log/YOUR_ACCESS_LOG_HERE.log; \& error_log /var/log/YOUR_ERROR_LOG_HERE.log info; \& \& root YOUR_ROOT_PROJECT/public; \& location / { \& try_files $uri @proxy; \& access_log off; \& expires max; \& } \& \& location @proxy { \& proxy_set_header Host $http_host; \& proxy_set_header X\-Forwarded\-Host $host; \& proxy_set_header X\-Real\-IP $remote_addr; \& proxy_set_header X\-Forwarded\-For $proxy_add_x_forwarded_for; \& proxy_pass http://backendurl; \& } \& \& } .Ve .PP You will need plackup to start a worker listening on a socket : .PP .Vb 3 \& cd YOUR_PROJECT_PATH \& sudo \-u www plackup \-E production \-s Starman \-\-workers=2 \e \& \-l THE_PATH_OF_YOUR_PLACKUP_SOCKET_HERE.sock \-a bin/app.pl .Ve .PP A good way to start this is to use \f(CW\*(C`daemontools\*(C'\fR and place this line with all environments variables in the \*(L"run\*(R" file. .SH "NON-STANDARD STEPS" .IX Header "NON-STANDARD STEPS" .SS "Turning off warnings" .IX Subsection "Turning off warnings" The \f(CW\*(C`warnings\*(C'\fR pragma is already used when one loads Dancer2. However, if you \fIreally\fR do not want the \f(CW\*(C`warnings\*(C'\fR pragma (for example, due to an undesired warning about use of undef values), add a \f(CW\*(C`no warnings\*(C'\fR pragma to the appropriate block in your module or psgi file. .SH "AUTHOR" .IX Header "AUTHOR" Dancer Core Developers .SH "COPYRIGHT AND LICENSE" .IX Header "COPYRIGHT AND LICENSE" This software is copyright (c) 2014 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.