Dancer2 is a free and open source web application framework written in Perl.
It's a complete rewrite of Dancer, based on Moo and using a more robust and extensible fully-OO design.
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.
Installation of Dancer2 is simple:
perl -MCPAN -e 'install Dancer2'
Thanks to the magic of cpanminus, if you do not have CPAN.pm configured, or just want a quickfire way to get running, the following should work, at least on Unix-like systems:
wget -O - http://cpanmin.us | sudo perl - Dancer2
(If you don't have root access, omit the 'sudo', and cpanminus will install Dancer2 and prereqs into ~/perl5
.)
Create a web application using the dancer script:
$ dancer2 -a mywebapp && cd mywebapp
+ mywebapp
+ mywebapp/config.yml
+ mywebapp/MANIFEST.SKIP
+ mywebapp/Makefile.PL
+ mywebapp/lib
+ mywebapp/lib/mywebapp.pm
+ mywebapp/public
+ mywebapp/public/500.html
+ mywebapp/public/favicon.ico
+ mywebapp/public/dispatch.cgi
+ mywebapp/public/404.html
+ mywebapp/public/dispatch.fcgi
+ mywebapp/public/images
+ mywebapp/public/images/perldancer.jpg
+ mywebapp/public/images/perldancer-bg.jpg
+ mywebapp/public/css
+ mywebapp/public/css/error.css
+ mywebapp/public/css/style.css
+ mywebapp/public/javascripts
+ mywebapp/public/javascripts/jquery.js
+ mywebapp/t
+ mywebapp/t/001_base.t
+ mywebapp/t/002_index_route.t
+ mywebapp/bin
+ mywebapp/bin/app.psgi
+ mywebapp/views
+ mywebapp/views/index.tt
+ mywebapp/views/layouts
+ mywebapp/views/layouts/main.tt
+ mywebapp/environments
+ mywebapp/environments/development.yml
+ mywebapp/environments/production.yml
Because Dancer2 is a PSGI web application framework, you can use the plackup
tool (provided by Plack) for launching the application:
plackup -p 5000 bin/app.psgi
View the web application at:
http://localhost:5000
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 routes. A route handler is composed by an HTTP method, a path pattern and a code block. strict
and warnings
pragmas are also imported with Dancer2.
The code block given to the route handler has to return a string which will be used as the content to render to the client.
Routes are defined for a given HTTP method. For each method supported, a keyword is exported by the module.
Here are some of the standard HTTP methods which you can use to define your route handlers.
- GET The GET method retrieves information, and is the most common
-
GET requests should be used for typical "fetch" requests - retrieving information. They should not be used for requests which change data on the server or have other effects.
When defining a route handler for the GET method, Dancer2 automatically defines a route handler for the HEAD method (in order to honour HEAD requests for each of your GET route handlers).
To define a GET action, use the get keyword.
- POST The POST method is used to create a resource on the server.
-
To define a POST action, use the post keyword.
- PUT The PUT method is used to replace an existing resource.
-
To define a PUT action, use the put keyword.
a PUT 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 PATCH request is used.
- PATCH The PATCH method updates some attributes of an existing resource.
-
To define a PATCH action, use the patch keyword.
- DELETE The DELETE method requests that the origin server delete the resource identified by the Request-URI.
-
To define a DELETE action, use the del keyword.
Routes can use any
to match all, or a specified list of HTTP methods.
The following will match any HTTP request to the path /myaction
:
any '/myaction' => sub {
# code
}
The following will match GET or POST requests to /myaction
:
any ['get', 'post'] => '/myaction' => sub {
# code
};
For convenience, any route which matches GET requests will also match HEAD requests.
The route action is the code reference declared. It can access parameters through the params
keyword, which returns a hashref. This hashref is a merge of the route pattern matches and the request params.
You can have more details about how params are built and how to access them in the Dancer2::Core::Request documentation.
To control what happens when a web request is received by your webapp, you'll need to declare routes
. A route declaration indicates which HTTP method(s) it is valid for, the path it matches (e.g. /foo/bar
), and a coderef to execute, which returns the response.
get '/hello/:name' => sub {
return "Hi there " . params->{name};
};
The above route specifies that, for GET requests to /hello/...
, the code block provided should be executed.
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 HTTP POST requests, the content of the POST body.
As seen above, you can use :somename
in a route's path to capture part of the path; this will become available by calling params.
So, for a web app where you want to display information on a company, you might use something like:
get '/company/view/:companyid' => sub {
my $company_id = params->{companyid};
# Look up the company and return appropriate page
};
You can also declare wildcards in a path and retrieve the values they matched with the splat keyword:
get '/*/*' => sub {
my ($action, $id) = splat;
if (my $action eq 'view') {
return display_item($id);
} elsif ($action eq 'delete') {
return delete_item($id);
} else {
status 'not_found';
return "What?";
}
};
A route can combine named (token) matching and wildcard matching. This is useful when chaining actions:
get '/team/:team/**' => sub {
var team => param('team');
pass;
};
prefix '/team/:team';
get '/player/*' => sub {
my ($player) = splat;
# etc...
};
get '/score' => sub {
return score_for( vars->{'team'} );
};
A route can be defined with a Perl regular expression.
In order to tell Dancer2 to consider the route as a real regexp, the route must be defined explicitly with qr{}
, like the following:
get qr{/hello/([\w]+)} => sub {
my ($name) = splat;
return "Hello $name";
};
For Perl 5.10+, a route regex may use named capture groups. The captures
keyword will return a reference to a copy of %+
.
Routes may include some matching conditions (on content_type, agent, user_agent, content_length and path_info):
get '/foo', {agent => 'Songbird (\d\.\d)[\d\/]*?'} => sub {
'foo method for songbird'
}
get '/foo' => sub {
'all browsers except songbird'
}
A prefix can be defined for each route handler, like this:
prefix '/home';
From here, any route handler is defined to /home/*
get '/page1' => sub {}; # will match '/home/page1'
You can unset the prefix value
prefix '/'; # or: prefix undef;
get '/page1' => sub {}; # will match /page1
Alternatively, to prevent you from ever forgetting to undef the prefix, you can use lexical prefix like this:
prefix '/home' => sub {
get '/page1' => sub {}; # will match '/home/page1'
}; ## prefix reset to previous value on exit
get '/page1' => sub {}; # will match /page1
An action can choose not to serve the current request and ask Dancer2 to process the request with the next matching route.
This is done with the pass keyword, like in the following example
get '/say/:word' => sub {
return pass if (params->{word} =~ /^\d+$/);
"I say a word: ".params->{word};
};
get '/say/:number' => sub {
"I say a number: ".params->{number};
};
Hooks are code references (or anonymous subroutines) that are triggered at specific moments during the resolution of a request.
Many of them are supported by the core but plugins and engines can also define their own.
before
hooks are evaluated before each request within the context of the request and receives as argument the app (a Dancer2::Core::App object).It's possible to define variables which will be accessible in the action blocks with the keyword
var
.hook before => sub { var note => 'Hi there'; }; get '/foo/*' => sub { my ($match) = splat; # 'oversee'; vars->{note}; # 'Hi there' };
For another example, this can be used along with session support to easily give non-logged-in users a login page:
hook before => sub { if (!session('user') && request->dispatch_path !~ m{^/login}) { # Pass the original path requested along to the handler: forward '/login', { requested_path => request->dispatch_path }; } };
The request keyword returns the current Dancer2::Core::Request object representing the incoming request.
after
hooks are evaluated after the response has been built by a route handler, and can alter the response itself, just before it's sent to the client.This hook runs after a request has been processed, but before the response is sent.
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.
The hook is given the response object as its first argument:
hook after => sub { content q{The "after" hook can alter the response's content here!}; };
before_template_render
hooks are called whenever a template is going to be processed, they are passed the tokens hash which they can alter.hook before_template_render => sub { my $tokens = shift; $tokens->{foo} = 'bar'; }
The tokens hash will then be passed to the template with all the modifications performed by the hook. This is a good way to setup some global vars you like to have in all your templates, like the name of the user logged in or a section name.
after_template_render
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.hook after_template_render => sub { my $ref_content = shift; my $content = ${$ref_content}; # do something with $content $ref_content = \$content; };
before_layout_render
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.hook before_layout_render => sub { my ($tokens, $ref_content) = @_; $tokens->{new_stuff} = 42; $ref_content = \"new content"; };
after_layout_render
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.hook after_layout_render => sub { my $ref_content = shift; # do something with ${ $ref_content }, which reflects directly # in the caller };
It's common to want to use sessions to give your web applications state; for instance, allowing a user to log in, creating a session, and checking that session on subsequent requests.
To make use of sessions, you must first enable the session engine - pick the session engine you want to use, then declare it in your config file like this:
session: Simple
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.
You can also use the Dancer2::Session::YAML backend included with Dancer2, which stores session data on disc in YAML files (since YAML is a nice human-readable format, it makes inspecting the contents of sessions a breeze):
session: YAML
Or, to enable session support from within your code,
set session => 'YAML';
However, controlling settings is best done from your config file.
'YAML' 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 YAML backend is simple and easy to use.
You can then use the session keyword to manipulate the session:
Storing data in the session is as easy as:
session varname => 'value';
Retrieving data from the session is as easy as:
session('varname')
Or, alternatively,
session->read("varname")
For disc-based session backends like Dancer2::Session::YAML, Dancer2::Session::Storable etc., session files are written to the session dir specified by the session_dir
setting, which defaults to ./sessions
if not specifically set.
If you need to control where session files are created, you can do so quickly and easily within your config file, for example:
session: YAML
engines:
session:
YAML:
session_dir: /tmp/dancer-sessions
If the directory you specify does not exist, Dancer2 will attempt to create it for you.
When you're done with your session, you can destroy it:
app->destroy_session
A common requirement is to check the user is logged in, and, if not, require them to log in before continuing.
This can easily be handled using a before hook to check their session:
use Dancer2;
set session => "Simple";
hook before => sub {
if (!session('user') && request->dispatch_path !~ m{^/login}) {
forward '/login', { requested_path => request->dispatch_path };
}
};
get '/' => sub { return "Home Page"; };
get '/secret' => sub { return "Top Secret Stuff here"; };
get '/login' => sub {
# Display a login page; the original URL they requested is available as
# param('requested_path'), so could be put in a hidden field in the form
template 'login', { path => param('requested_path') };
};
post '/login' => sub {
# Validate the username and password they supplied
if (param('user') eq 'bob' && param('pass') eq 'letmein') {
session user => param('user');
redirect param('path') || '/';
} else {
redirect '/login?failed=1';
}
};
dance();
Here is what the corresponding login.tt
file should look like. You should place it in a directory called views/
:
<html>
<head>
<title>Session and logging in</title>
</head>
<body>
<form action='/login' method='POST'>
User Name : <input type='text' name='user'/>
Password: <input type='password' name='pass' />
<!-- Put the original path requested into a hidden
field so it's sent back in the POST and can be
used to redirect to the right page after login -->
<input type='hidden' name='path' value='[% path %]'/>
<input type='submit' value='Login' />
</form>
</body>
</html>
Of course, you'll probably want to validate your users against a database table, or maybe via IMAP/LDAP/SSH/POP3/local system accounts via PAM etc. Authen::Simple is probably a good starting point here!
A simple working example of handling authentication against a database table yourself (using Dancer2::Plugin::Database which provides the database
keyword, and Crypt::SaltedHash to handle salted hashed passwords (well, you wouldn't store your users passwords in the clear, would you?)) follows:
post '/login' => sub {
my $user = database->quick_select('users',
{ username => params->{user} }
);
if (!$user) {
warning "Failed login for unrecognised user " . params->{user};
redirect '/login?failed=1';
} else {
if (Crypt::SaltedHash->validate($user->{password}, params->{pass}))
{
debug "Password correct";
# Logged in successfully
session user => $user;
redirect params->{path} || '/';
} else {
debug("Login failed - password incorrect for " . params->{user});
redirect '/login?failed=1';
}
}
};
Get complete hash stored in session:
my $hash = session;
In Dancer 2, a session backend consumes the role Dancer::Core::Role::SessionFactory.
The following example using the Reddis session demonstrates how session engines are written in Dancer 2.
First thing to do is to create the class for the session engine, we'll name it Dancer::Session::Redis
:
package Dancer::Session::Redis;
use Moo;
with 'Dancer::Core::Role::SessionFactory';
we want our backend to have a handle over a Redis connection. To do that, we'll create an attribute redis
use JSON;
use Redis;
use Dancer::Core::Types; # brings helper for types
has redis => (
is => 'rw',
isa => InstanceOf['Redis'],
lazy => 1,
builder => '_build_redis',
);
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.
sub _build_redis {
my ($self) = @_;
Redis->new(
server => $self->server,
password => $self->password,
encoding => undef,
);
}
Two more attributes, server
and password
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.
# config.yml
...
engines:
session:
Redis:
server: foo.mydomain.com
password: S3Cr3t
The server and password entries are now passed to the constructor of the Redis session engine and can be accessed from there.
has server => (is => 'ro', required => 1);
has password => (is => 'ro');
Next, we define the subroutine _retrieve
which will return a session object for a session ID it has passed. Since in this case, sessions are going to be stored in Redis, the session ID will be the key, the session the value. So retrieving is as easy as doing a get and decoding the JSON string returned:
sub _retrieve {
my ($self, $session_id) = @_;
my $json = $self->redis->get($session_id);
my $hash = from_json( $json );
return bless $hash, 'Dancer::Core::Session';
}
The _flush
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 Dancer::Core::Session
object and is supposed to store it.
sub _flush {
my ($self, $session) = @_;
my $json = to_json( { %{ $session } } );
$self->redis->set($session->id, $json);
}
For the _destroy
method which is supposed to remove a session from the backend, deleting the key from Redis is enough.
sub _destroy {
my ($self, $session_id) = @_;
$self->redis->del($session_id);
}
The _sessions
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.
sub _sessions {
my ($self) = @_;
my @keys = $self->redis->keys('*');
return \@keys;
}
The session engine is now ready.
When Dancer 2 executes a route handler to process a request, it creates a Dancer::Core::Context object. This context is passed to all the components of Dancer that can play with it, to build the response. For instance, a before filter will receive that context object.
The session handle for the current client, is thus found in the context. Thus, the builder only has to look if the client has a dancer.session cookie, and if so, try to retrieve the session from the storage engine, with the value of the cookie (the session ID).
has session => (
is => 'rw',
isa => Session,
lazy => 1,
builder => '_build_session',
);
sub _build_session {
my ($self) = @_;
my $session;
# Find the session engine
my $engine = $self->app->setting('session');
croak "No session engine defined, cannot use session."
if ! defined $engine;
# find the session cookie if any
my $session_id;
my $session_cookie = $self->cookie('dancer.session');
if (defined $session_cookie) {
$session_id = $session_cookie->value;
}
# if we have a session cookie, try to retrieve the session
if (defined $session_id) {
eval { $session = $engine->retrieve(id => $session_id) };
croak "Fail to retreive session: $@"
if $@ && $@ !~ /Unable to retrieve session/;
}
# create the session if none retrieved
return $session ||= $engine->create();
}
So the very first time session is called, the object is either retrieved from the backend, or a new Dancer::Core::Session
is created, and stored in the context. Then, a before filter makes sure a cookie dancer.session is added to the headers.
# Hook to add the session cookie in the headers, if a session is defined
$self->add_hook(Dancer::Core::Hook->new(
name => 'core.app.before_request',
code => sub {
my $context = shift;
# make sure an engine is defined, if not, nothing to do
my $engine = $self->setting('session');
return if ! defined $engine;
# push the session in the headers
$context->response->push_header('Set-Cookie',
$context->session->cookie->to_header);
}
));
At this time, the user's code comes into play, using the session keyword
sub session {
my ($self, $key, $value) = @_;
my $session = $self->context->session;
croak "No session available, a session engine needs to be set"
if ! defined $session;
# return the session object if no key
return $session if @_ == 1;
# read if a key is provided
return $session->read($key) if @_ == 2;
# write to the session
$session->write($key => $value);
}
To conclude, an after
filter is set to call the flush method of the storage backend.
# Hook to flush the session at the end of the request, this way, we're sure we
# flush only once per request
$self->add_hook(
Dancer::Core::Hook->new(
name => 'core.app.after_request',
code => sub {
# make sure an engine is defined, if not, nothing to do
my $engine = $self->setting('session');
return if ! defined $engine;
return if ! defined $self->context;
$engine->flush(session => $self->context->session);
},
)
);
The code for this can be found on Github
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.
Your route handlers can use the template keyword to render templates.
It's possible to render the action's content with a template, this is called a view. The appdir/views
directory is the place where views are located.
You can change this location by changing the setting 'views'. For instance if your templates are located in the 'templates' directory, do the following:
set views => path(dirname(__FILE__), 'templates');
By default, the internal template engine 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.
In order to render a view, just call the template keyword at the end of the action by giving the view name and the HASHREF of tokens to interpolate in the view (note that for convenience, the request, session, params and vars are automatically accessible in the view, named request
, session
, params
and vars
) - for example:
hook before => sub { var time => scalar(localtime) };
get '/hello/:name' => sub {
my $name = params->{name};
template 'hello.tt', { name => $name };
};
The template hello.tt
could contain, for example:
<p>Hi there, [% name %]!</p>
<p>You're using [% request.user_agent %]</p>
[% IF session.username %]
<p>You're logged in as [% session.username %]</p>
[% END %]
It's currently [% vars.time %]
For a full list of the tokens automatically added to your template (like session
, request
and vars
, refer to Dancer2::Core::Role::Template).
By default, views use a .tt extension. This can be overridden by setting the extension
attribute in the template engine configuration:
set engines => {
template => {
template_toolkit => {
extension => 'foo',
},
},
};
A layout is a special view, located in the 'layouts' directory (inside the views directory) which must have a token named content
. That token marks the place where to render the action view. This lets you define a global layout for your actions, and have each individual view contain only specific content. This is a good thing to avoid lots of needless duplication of HTML :)
Here is an example of a layout: views/layouts/main.tt
:
<html>
<head>...</head>
<body>
<div id="header">
...
</div>
<div id="content">
[% content %]
</div>
</body>
</html>
You can tell your app which layout to use with layout: name
in the config file, or within your code:
set layout => 'main';
You can control which layout to use (or whether to use a layout at all) for a specific request without altering the layout setting by passing an options hashref as the third param to the template keyword:
template 'index.tt', {}, { layout => undef };
If your application is not mounted under root (/
), you can use a before_template
hook instead of hardcoding the path into your application for your CSS, images and JavaScript:
hook before_template_render => sub {
my $tokens = shift;
$tokens->{uri_base} = request->base->path;
};
Then in your layout, modify your CSS inclusion as follows:
<link rel="stylesheet" href="[% uri_base %]/css/style.css" />
From now on you can mount your application wherever you want, without any further modification of the CSS inclusion.
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 UTF-8. So, if you are using template toolkit, your config file will look like this:
charset: UTF-8
engines:
template:
template_toolkit:
ENCODING: utf8
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 dance()
method.
Other ways are possible: for example, you can define all your settings in the file appdir/config.yml
. For this, you must have installed the YAML module, and of course, write the config file in YAML.
That's better than the first option, but it's still not perfect as you can't switch easily from an environment to another without rewriting the config file.
A better solution is to have one config.yml
file with default global settings, like the following:
# appdir/config.yml
logger: 'file'
layout: 'main'
And then write as many environment files as you like in appdir/environments
. That way, the appropriate environment config file will be loaded according to the running environment (if none is specified, it will be 'development').
Note that you can change the running environment using the --environment
command line switch.
Typically, you'll want to set the following values in a development config file:
# appdir/environments/development.yml
log: 'debug'
startup_info: 1
show_errors: 1
And in a production one:
# appdir/environments/production.yml
log: 'warning'
startup_info: 0
show_errors: 0
A Dancer2 application can use the config
keyword to easily access the settings within its config file, for instance:
get '/appname' => sub {
return "This is " . config->{appname};
};
This makes keeping your application's settings all in one place simple and easy - you shouldn't need to worry about implementing all that yourself :)
You may want to access your webapp's configuration from outside your webapp. You could, of course, use the YAML module of your choice and load your webapps's config.yml
, but chances are that this is not convenient.
Use Dancer2 instead. You can simply use the values from config.yml
and some additional default values:
# bin/show_app_config.pl
use Dancer2;
print "template:".config->{template}."\n"; # simple
print "log:".config->{log}."\n"; # undef
Note that config->{log}
should result in an uninitialized warning on a default scaffold since the environment isn't loaded and log is defined in the environment and not in config.yml
. Hence undef
.
Dancer2 will load your config.yml
configuration file along with the correct environment file located in your environments
directory.
The environment is determined by two environment variables in the following order:
DANCER_ENVIRONMENT
PLACK_ENV
If neither of those is set, it will default to loading the development environment (typically $webapp/environment/development.yml
).
If you wish to load a different environment, you need to override these variables.
You can call your script with the environment changed:
$ PLACK_ENV=production perl bin/show_app_config.pl
Or you can override them directly in the script (less recommended):
BEGIN { $ENV{'DANCER_ENVIRONMENT'} = 'production' }
use Dancer2;
...
It's possible to change almost every parameter of the application via the settings mechanism.
A setting is a key/value pair assigned by the keyword set:
set setting_name => 'setting_value';
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).
An app in Dancer2 uses the class name (defined by the package
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:
package MyApp::User {
use Dancer2;
set serializer => 'JSON';
get '/view' => sub {...};
}
package MyApp::User::Edit {
use Dancer2;
get '/edit' => sub {...};
}
These are two different Dancer2 Apps. They have different scopes, contexts, and thus different engines. While MyApp::User
has a serializer defined, MyApp::User::Edit
will not have that configuration.
By using the import option appname
, we can ask Dancer2 to extend an App without creating a new one:
package MyApp::User {
use Dancer2;
set serializer => 'JSON';
get '/view' => sub {...};
}
package MyApp::User::Edit {
use Dancer2 appname => 'MyApp::User'; # extending MyApp::User
get '/edit' => sub {...};
}
The import option appname
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.
# app.pl
use MyApp::User;
use MyApp::User::Edit;
# single application composed of routes provided in multiple files
MyApp::User->to_app;
This way only one class needs to be loaded while creating an app:
# app.pl:
use MyApp::User;
MyApp::User->to_app;
It's possible to log messages generated by the application and by Dancer2 itself.
To start logging, select the logging engine you wish to use with the logger
setting; Dancer2 includes built-in log engines named file
and console
, which log to a logfile and to the console respectively.
To enable logging to a file, add the following to your config file:
logger: 'file'
Then you can choose which kind of messages you want to actually log:
log: 'core' # will log debug, info, warnings, errors,
# and messages from Dancer2 itself
log: 'debug' # will log debug, info, warning and errors
log: 'info' # will log info, warning and errors
log: 'warning' # will log warning and errors
log: 'error' # will log only errors
If you're using the file
logging engine, a directory appdir/logs
will be created and will host one logfile per environment. The log message contains the time it was written, the PID of the current process, the message and the caller information (file and line).
Just call debug, info, warning or error with your message:
debug "This is a debug message from my app.";
At the simplest, your Dancer2 app can run standalone, operating as its own webserver using HTTP::Server::PSGI.
Simply fire up your app:
$ plackup bin/app.psgi
>> Listening on 0.0.0.0:3000
== Entering the dance floor ...
Point your browser at it, and away you go!
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.
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:
$ plackup -L Shotgun bin/app.psgi
HTTP::Server::PSGI: Accepting connections at http://0:5000/
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.
Please note that this is not recommended for production for performance reasons. This is the Dancer2 replacement solution of the old Dancer experimental auto_reload
option.
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:
> set PLACK_SHOTGUN_MEMORY_LEAK=1 && plackup -L Shotgun bin\app.psgi
HTTP::Server::PSGI: Accepting connections at http://0:5000/
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.
Start by adding the following to your apache configuration (httpd.conf
or sites-available/*site*
):
<VirtualHost *:80>
ServerName www.example.com
DocumentRoot /srv/www.example.com/public
ServerAdmin [email protected]
<Directory "/srv/www.example.com/public">
AllowOverride None
Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
Order allow,deny
Allow from all
AddHandler cgi-script .cgi
</Directory>
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
</VirtualHost>
Note that when using fast-cgi your rewrite rule should be:
RewriteRule ^(.*)$ /dispatch.fcgi$1 [QSA,L]
Here, the mod_rewrite magic for Pretty-URLs is directly put in Apache's configuration. But if your web server supports .htaccess
files, you can drop those lines in a .htaccess
file.
To check if your server supports mod_rewrite type apache2 -l
to list modules. To enable mod_rewrite
on Debian or Ubuntu, run a2enmod rewrite
. Place following code in a file called .htaccess
in your application's root folder:
# BEGIN dancer application htaccess
RewriteEngine On
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteRule (.*) /dispatch.cgi$1 [L]
# END dancer application htaccess
Now you can access your Dancer2 application URLs as if you were using the embedded web server:
http://localhost/
This option is a no-brainer, easy to setup, low maintenance but serves requests slower than all other options.
You can use the same technique to deploy with FastCGI, by just changing the line:
AddHandler cgi-script .cgi
to:
AddHandler fastcgi-script .fcgi
Of course remember to update your rewrite rules, if you have set any:
RewriteRule (.*) /dispatch.fcgi$1 [L]
If you want to deploy multiple applications under the same VirtualHost
(using one application per directory, for example) you can use the following example Apache configuration.
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/VirtualHost
.
<VirtualHost *:80>
ServerName localhost
DocumentRoot "/path/to/rootdir"
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
<Directory "/path/to/rootdir">
AllowOverride None
Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
Order allow,deny
Allow from all
AddHandler fastcgi-script .fcgi
</Directory>
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]
</VirtualHost>
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.
To run as a CGI app on lighttpd, just create a soft link to the dispatch.cgi
script (created when you run dancer -a MyApp
) inside your system's cgi-bin
folder. Make sure mod_cgi
is enabled.
ln -s /path/to/MyApp/public/dispatch.cgi /usr/lib/cgi-bin/mycoolapp.cgi
Make sure mod_fcgi
is enabled. You also must have FCGI installed.
This example configuration uses TCP/IP:
$HTTP["url"] == "^/app" {
fastcgi.server += (
"/app" => (
"" => (
"host" => "127.0.0.1",
"port" => "5000",
"check-local" => "disable",
)
)
)
}
Launch your application:
plackup -s FCGI --port 5000 bin/app.psgi
This example configuration uses a socket:
$HTTP["url"] =~ "^/app" {
fastcgi.server += (
"/app" => (
"" => (
"socket" => "/tmp/fcgi.sock",
"check-local" => "disable",
)
)
)
}
Launch your application:
plackup -s FCGI --listen /tmp/fcgi.sock bin/app.psgi
Plack::Test receives a common web request (using standard HTTP::Request objects), fakes a web server in order to create a proper PSGI request, and sends it to the web application. When the web application returns a PSGI response (which Dancer applications do), it will then convert it to a common web response (as a standard HTTP::Response object).
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.
Assuming there is a web application:
# MyApp.pm
package MyApp;
use Dancer2;
get '/' => sub {'OK'};
1;
The following test base.t is created:
# base.t
use strict;
use warnings;
use Test::More tests => 2;
use Plack::Test;
use HTTP::Request;
use MyApp;
Creating a coderef for the application using the to_app
keyword:
my $app = MyApp->to_app;
Creating a test object from Plack::Test for the application:
my $test = Plack::Test->create($app);
Creating the first request object and sending it to the test object to receive a response:
my $request = HTTP::Request->new( GET => '/' );
my $response = $test->request($request);
It can now be tested:
ok( $response->is_success, '[GET /] Successful request' );
is( $response->content, 'OK', '[GET /] Correct content' );
# 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 '/' );
ok( $response->is_success, '[GET /] Successful request' );
is( $response->content, 'OK', '[GET /] Correct content' );
done_testing();
Tests can be separated using Test::More's subtest
functionality, thus creating multiple self-contained tests that don't overwrite each other.
Assuming we have a different app that has two states we want to test:
# MyApp.pm
package MyApp;
use Dancer2;
set serializer => 'JSON';
get '/' => sub {
my $user = param('user');
$user and return { user => $user };
return {};
};
1;
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
# 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 'A empty request' => sub {
my $res = $test->request( GET '/' );
ok( $res->is_success, 'Successful request' );
is( $res->content '{}', 'Empty response back' );
};
subtest 'Request with user' => sub {
my $res = $test->request( GET '/?user=sawyer_x' );
ok( $res->is_success, 'Successful request' );
is( $res->content '{"user":"sawyer_x"}', 'Empty response back' );
};
done_testing();
To handle cookies, which are mostly used for maintaining sessions, the following modules can be used: Test::WWW::Mechanize::PSGI LWP::Protocol::PSGI HTTP::Cookies
Taking the previous test, assuming it actually creates and uses cookies for sessions:
# ... all the use statements
use HTTP::Cookies;
my $jar = HTTP::Cookies->new;
my $test = Plack::Test->create( MyApp->to_app );
subtest 'A empty request' => sub {
my $res = $test->request( GET '/' );
ok( $res->is_success, 'Successful request' );
is( $res->content '{}', 'Empty response back' );
$jar->extract_cookies($res);
ok( $jar->as_string, 'We have cookies!' );
};
subtest 'Request with user' => sub {
my $req = GET '/?user=sawyer_x';
$jar->add_cookie_header($req);
my $res = $test->request($req);
ok( $res->is_success, 'Successful request' );
is( $res->content '{"user":"sawyer_x"}', 'Empty response back' );
$jar->extract_cookies($res);
ok( ! $jar->as_string, 'All cookies deleted' );
};
done_testing();
Here a cookie jar is created, all requests and responses, existing cookies, as well as cookies that were deleted by the response, are checked.
By importing Dancer2 in the command line scripts, there is full access to the configuration using the imported keywords:
use strict;
use warnings;
use Test::More;
use Plack::Test;
use HTTP::Request::Common;
use MyApp;
use Dancer2;
my $appname = config->{'appname'};
diag "Testing $appname";
# ...
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.
The benefits are multifold:
- Local Directory copy
-
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.
- Sync versions
-
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.
- Carry only the requirement, not bundled modules
-
Instead of bundling the modules, you only actually bundle the requirements. Carton builds them for you when you need it.
First set up a new app:
$ dancer2 -a MyApp
...
Delete the files that are not needed:
$ rm -f Makefile.PL MANIFEST MANIFEST.SKIP
Create a git repo:
$ git init && git add . && git commit -m "initial commit"
Add a requirement using the cpanfile format:
$ cat > cpanfile
requires 'Dancer2' => 0.155000;
requires 'Template' => 0;
recommends 'URL::Encode::XS' => 0;
recommends 'CGI::Deurl::XS' => 0;
recommends 'HTTP::Parser::XS' => 0;
Ask carton to set it up:
$ carton install
Installing modules using [...]
Successfully installed [...]
...
Complete! Modules were install into [...]/local
Now we have two files: cpanfile and cpanfile.snapshot. We add both of them to our Git repository and we make sure we don't accidentally add the local/ directory Carton created which holds the modules it installed:
$ echo local/ >> .gitignore
$ git add .gitignore cpanfile cpanfile.snapshot
$ git commit -m "Start using carton"
When we want to update the versions on the production machine, we simply call:
$ carton install --deployment
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 CPAN.
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.
As long as your application is pure-Perl, you could create a single file with your application and all of Dancer2 in it.
The following example will demonstrate how this can be done:
Assuming we have an application in lib/MyApp.pm:
package MyApp;
use Dancer2;
get '/' => sub {'OK'};
1;
And we have a handler in bin/app.pl:
use strict;
use warnings;
use FindBin;
use lib "$FindBin::Bin/../lib";
use MyApp;
MyApp->to_app;
To fatpack it, we begin by tracing the script:
$ fatpack trace bin/app.pl
This creates a fatpacker.trace file. From this we create the packlists:
$ fatpack packlists-for `cat fatpacker.trace` > packlists
The packlists are stored in a file called packlists.
Now we create the tree using the following command:
$ fatpack tree `cat packlists`
The tree is created under the directory fatlib.
Now we create a file containing the dependency tree, and add our script to it, using the following command:
$ (fatpack file; cat bin/app.pl) > myapp.pl
This creates a file called myapp.pl with everything in it. Dancer2 uses MIME::Types which has a database of all MIME 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:
$ cp fatlib/MIME/types.db .
If you want to use Plack middlewares, you need to enable them using Plack::Builder as such:
# in app.psgi or any other handler
use Dancer2;
use MyWebApp;
use Plack::Builder;
builder {
enable 'Deflater';
enable 'Session', store => 'File';
enable 'Debug', panels => [ qw<DBITrace Memory Timer> ];
dance;
};
The nice thing about this setup is that it will work seamlessly through Plack or through the internal web server.
# load dev web server (without middlewares)
perl -Ilib app.psgi
# load plack web server (with middlewares)
plackup -I lib app.psgi
You do not need to provide different files for either server.
If you want to set up a middleware for a specific path, you can do that using Plack::Builder which uses Plack::App::URLMap:
# in your app.psgi or any other handler
use Dancer2;
use MyWebApp;
use Plack::Builder;
my $special_handler = sub { ... };
builder {
mount '/' => dance;
mount '/special' => $special_handler;
};
A number of Perl web servers supporting PSGI are available on CPAN:
- Starman
-
Starman
is a high performance web server, with support for preforking, signals, multiple interfaces, graceful restarts and dynamic worker pool configuration. - Twiggy
-
Twiggy
is anAnyEvent
web server, it's light and fast. - Corona
-
Corona
is aCoro
based web server.
To start your application, just run plackup (see Plack and specific servers above for all available options):
$ plackup bin/app.psgi
$ plackup -E deployment -s Starman --workers=10 -p 5001 -a bin/app.psgi
As you can see, the scaffolded Perl script for your app can be used as a PSGI startup file.
Content compression (gzip, deflate) can be easily enabled via a Plack middleware (see "Plack::Middleware" in Plack): Plack::Middleware::Deflater. It's a middleware to encode the response body in gzip or deflate, based on the Accept-Encoding
HTTP request header.
Enable it as you would enable any Plack middleware. First you need to install Plack::Middleware::Deflater, then in the handler (usually app.psgi) edit it to use Plack::Builder, as described above:
use Dancer2;
use MyWebApp;
use Plack::Builder;
builder {
enable 'Deflater';
dance;
};
To test if content compression works, trace the HTTP 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 Content-Encoding
set to gzip
or deflate
.
You can use Plack::Builder to mount multiple Dancer2 applications on a PSGI webserver like Starman.
Start by creating a simple app.psgi file:
use OurWiki; # first app
use OurForum; # second app
use Plack::Builder;
builder {
mount '/wiki' => OurWiki->psgi_app;
mount '/forum' => OurForum->psgi_app;
};
and now use Starman
plackup -a app.psgi -s Starman
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.
You can run your app from Apache using PSGI (Plack), with a config like the following:
<VirtualHost myapp.example.com>
ServerName www.myapp.example.com
ServerAlias myapp.example.com
DocumentRoot /websites/myapp.example.com
<Directory /home/myapp/myapp>
AllowOverride None
Order allow,deny
Allow from all
</Directory>
<Location />
SetHandler perl-script
PerlResponseHandler Plack::Handler::Apache2
PerlSetVar psgi_app /websites/myapp.example.com/app.psgi
</Location>
ErrorLog /websites/myapp.example.com/logs/error_log
CustomLog /websites/myapp.example.com/logs/access_log common
</VirtualHost>
To set the environment you want to use for your application (production or development), you can set it this way:
<VirtualHost>
...
SetEnv DANCER_ENVIRONMENT "production"
...
</VirtualHost>
All that is needed for this is Dancer2::Plugin to provide all the keywords needed to write a plugin.
package Dancer2::Plugin::Kitteh;
use Dancer2::Plugin;
# we do nothing, just like most cats do
register_plugin;
1;
New keywords that the application will receive when it uses your plugin need to be introduced using the register
keyword:
register meow => sub {
my ( $dsl ) = plugin_args(@_);
my $app = $dsl->app;
};
The keyword receives an object which represents the DSL object the app is connected to. It can be used in order to access the Dancer2 core application connected to the user's scope.
Whether a keyword is app-global
, can also be controlled. It can be called from anywhere in an app or only from a route, which means during a request:
register meow => sub {
debug 'Meow!';
}, { is_global => 0 };
Some plugins generate routes from other routes, which makes them look a little bit like route decorators. Take Dancer2::Plugin::Auth::Tiny for example:
get '/private' => needs login => sub { ... };
This works by taking the route sub as a parameter and creating its own route which calls it.
package Dancer2::Plugin::OnTuesday;
# ABSTRACT: Make sure a route only works on Tuesday
use Dancer2::Plugin;
register on_tuesday => sub {
my ( $dsl, $route_sub, @args ) = plugin_args(@_);
my $day = (localtime)[6];
$day == 2 or return pass;
return $route_sub->( $dsl, @args );
};
register_plugin;
Now the plugin can be used as such:
package MyApp;
use Dancer2;
use Dancer2::Plugin::OnTuesday;
get '/' => on_tuesday => sub { ... };
# every other day
get '/' => sub { ... };
While a user can change the configuration using both the configuration file and the set
keyword, a single source is needed for all configuration options for the plugin. This is handled automatically using the plugin_setting
keyword:
register meow => sub {
my $dsl = shift;
my $vol = plugin_setting->{'volume'} || 3;
};