CONTENTS

NAME

Dancer2::Manual - A gentle introduction to Dancer2

VERSION

version 1.1.0

DESCRIPTION

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.

INSTALL

Installation of Dancer2 is simple, using your favourite method to install from CPAN, e.g.:

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.)

Dancer2 is also available as a package from the package repository of several distributions, for example on Debian/Ubuntu you should be able to just:

apt-get install libdancer2-perl

Do be aware, though, that distribution-packaged versions sometimes lag behind the most recent version on CPAN.

BOOTSTRAPPING A NEW APP

Create a web application using the dancer script:

$ dancer2 gen -a MyApp && cd MyApp
+ MyApp
+ MyApp/config.yml
+ MyApp/Makefile.PL
+ MyApp/MANIFEST.SKIP
+ MyApp/.dancer
+ MyApp/cpanfile
+ MyApp/bin
+ MyApp/bin/app.psgi
+ MyApp/environments
+ MyApp/environments/development.yml
+ MyApp/environments/production.yml
+ MyApp/lib
+ MyApp/lib/MyApp.pm
+ MyApp/public
+ MyApp/public/favicon.ico
+ MyApp/public/500.html
+ MyApp/public/dispatch.cgi
+ MyApp/public/404.html
+ MyApp/public/dispatch.fcgi
+ MyApp/public/css
+ MyApp/public/css/error.css
+ MyApp/public/css/style.css
+ MyApp/public/images
+ MyApp/public/images/perldancer.jpg
+ MyApp/public/images/perldancer-bg.jpg
+ MyApp/public/javascripts
+ MyApp/public/javascripts/jquery.js
+ MyApp/t
+ MyApp/t/001_base.t
+ MyApp/t/002_index_route.t
+ MyApp/views
+ MyApp/views/index.tt
+ MyApp/views/layouts
+ MyApp/views/layouts/main.tt

It creates a directory named after the name of the app, along with a configuration file, a views directory (where your templates and layouts will live), an environments directory (where environment-specific settings live), a module containing the actual guts of your application, and a script to start it. Finally, .dancer indicates the root directory of your app, making it easier for Dancer2 to determine the various paths it needs for finding resources and code within your application.

A default skeleton is used to bootstrap the new application, but you can use the -s option to provide another skeleton. For example:

$ dancer2 gen -a MyApp -s ~/mydancerskel

For an example of a skeleton directory check the default one available in the share/ directory of your Dancer2 distribution.

(In what follows we will refer to the directory in which you have created your Dancer2 application -- e.g., what MyApp was above -- as the appdir.)

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

USAGE

When Dancer2 is imported to a script, that script becomes a webapp, and at this point, all the script has to do is declare a list of routes. A route handler is composed by an HTTP method, a path pattern and a code block. strict, warnings and utf8 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.

HTTP Methods

Here are some of the standard HTTP methods which you can use to define your route handlers.

Handling multiple HTTP request methods

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.

Route Handlers

The route action is the code reference declared. It can access parameters through the specific route_parameters, query_parameters, and body_parameters keywords, which return a Hash::MultiValue object. This hashref is a merge of the route pattern matches and the request params.

You can find more details about how params are built and how to access them in the Dancer2::Core::Request documentation.

Declaring Routes

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 " . route_parameters->get('name');
};

The above route specifies that, for GET requests to /hello/..., the code block provided should be executed.

You can also provide routes with a name:

get 'hi_to' => '/hello/:name' => sub {...};

See "uri_for_route" in Dancer2::Manual::Keywords on how this can be used.

Retrieving request parameters

The query_parameters, route_parameters, and body_parameters keywords provide a Hash::MultiValue result from the three different parameters.

Named matching

A route pattern can contain one or more tokens (a word prefixed with ':'). Each token found in a route pattern is used as a named-pattern match. Any match will be set in the route parameters.

get '/hello/:name' => sub {
    return "Hey " . route_parameters->get('name') . ", welcome here!";
};

Tokens can be optional, for example:

get '/hello/:name?' => sub {
    my $name = route_parameters->get('name') // 'Whoever you are';
    return "Hello there, $name";
};

Named matching with type constraints

Type constraints can be added to tokens.

get '/user/:id[Int]' => sub {
    # matches /user/34 but not /user/jamesdean
    my $user_id = route_parameters->get('id');
};

get '/user/:username[Str]' => sub {
    # matches /user/jamesdean but not /user/34 since that is caught
    # by previous route
    my $username = route_parameters->get('username');
};

You can even use type constraints to add a regexp check:

get '/book/:date[StrMatch[qr{\d\d\d\d-\d\d-\d\d}]]' => sub {
    # matches /book/2014-02-04
    my $date = route_parameters->get('date');
};

The default type library is Dancer2::Core::Types but any type library built using Type::Tiny's Type::Library can be used instead. If you'd like to use a different default type library you must declare it in the configuration file, for example:

type_library: My::Type::Library

Alternatively you can specify the type library in which the type is defined as part of the route definition:

get '/user/:username[My::Type::Library::Username]' => sub {
    my $username = route_parameters->get('username');
};

This will load My::Type::Library and from it use the type Username. This allows types to be used that are not part of the type library defined by config's type_library.

More complex constructs are allowed such as:

get '/some/:thing[Int|MyDate]' => sub {
    ...;
};

See "lookup($name)" in Type::Registry for more details.

Wildcard Matching

A route can contain a wildcard (represented by a *). Each wildcard match will be placed in a list, which the splat keyword returns.

get '/download/*.*' => sub {
    my ($file, $ext) = splat;
    # do something with $file.$ext here
};

An extensive, greedier wildcard represented by ** (A.K.A. "megasplat") can be used to define a route. The additional path is broken down and returned as an arrayref:

get '/entry/*/tags/**' => sub {
    my ( $entry_id, $tags ) = splat;
    my @tags = @{$tags};
};

The splat keyword in the above example for the route /entry/1/tags/one/two would set $entry_id to 1 and $tags to ['one', 'two'].

Mixed named and wildcard matching

A route can combine named (token) matching and wildcard matching. This is useful when chaining actions:

get '/team/:team/**' => sub {
    var team => route_parameters->get('team');
    pass;
};

prefix '/team/:team';

get '/player/*' => sub {
    my ($player) = splat;

    # etc...
};

get '/score' => sub {
    return score_for( vars->{'team'} );
};

Regular Expression Matching

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";
};

A route regex may use named capture groups. The captures keyword will return a reference to a copy of %+.

Conditional Matching

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'
}

Prefix

A prefix can be defined for each route handler, like this:

prefix '/home';

From here, any route handler is defined to /home/*

get '/page1' => sub {}; # will match '/home/page1'

You can unset the prefix value

prefix '/'; # or: prefix undef;
get '/page1' => sub {}; # will match /page1

Alternatively, to prevent you from ever forgetting to undef the prefix, you can use lexical prefix like this:

prefix '/home' => sub {
  get '/page1' => sub {}; # will match '/home/page1'
}; ## prefix reset to previous value on exit

get '/page1' => sub {}; # will match /page1

Delayed responses (Async/Streaming)

Dancer2 can provide delayed (otherwise known as asynchronous) responses using the delayed keyword. These responses are streamed, although you can set the content all at once, if you prefer.

get '/status' => sub {
    delayed {
        response_header 'X-Foo' => 'Bar';

        # flush headers (in case of streaming)
        flush;

        # send content to the user
        content 'Hello, world!';

        # you can write more content
        # all streaming
        content 'Hello, again!';

        # when done, close the connection
        done;

        # do whatever you want else, asynchronously
        # the user socket closed by now
        ...
    };
};

If you are streaming (calling content several times), you must call flush first. If you're sending only once, you don't need to call flush.

Here is an example of using delayed responses with AnyEvent:

use Dancer2;
use AnyEvent;

my %timers;
my $count = 5;
get '/drums' => sub {
    delayed {
        print "Stretching...\n";
        flush; # necessary, since we're streaming

        $timers{'Snare'} = AE::timer 1, 1, delayed {
            $timers{'HiHat'} ||= AE::timer 0, 0.5, delayed {
                content "Tss...\n";
            };

            content "Bap!\n";

            if ( $count-- == 0 ) {
                %timers = ();
                content "Tugu tugu tugu dum!\n";
                done;

                print "<enter sound of applause>\n\n";
                $timers{'Applause'} = AE::timer 3, 0, sub {
                    # the DSL will not available here
                    # because we didn't call the "delayed" keyword
                    print "<applause dies out>\n";
                };
            }
        };
    };
};

If an error happens during a write operation, a warning will be issued to the logger.

You can handle the error yourself by providing an on_error handler:

get '/' => sub {
    delayed {
        flush;
        content "works";

        # ... user disconnected here ...

        content "fails";

        # ... error triggered ...

        done; # doesn't even get run
    } on_error => sub {
        # delayed{} not needed, DSL already available
        my ($error) = @_;
        # do something with $error
    };
};

Here is an example that asynchronously streams the contents of a CSV file:

use Dancer2;
use Text::CSV_XS  qw< csv >;
use Path::Tiny    qw< path >;
use JSON::MaybeXS qw< encode_json >;
# Create CSV parser
my $csv = Text::CSV_XS->new({
    binary    => 1,
    auto_diag => 1,
});
get '/' => sub {
    # delayed response:
    delayed {
        # streaming content
        flush;
        # Read each row and stream it in JSON
        my $fh = path('filename.csv')->openr_utf8;
        while ( my $row = $csv->getline($fh) ) {
            content encode_json $row;
        }
        # close user connection
        done;
    } on_error => sub {
        my ($error) = @_;
        warning 'Failed to stream to user: ' . request->remote_address;
    };
};

NOTE: If you just want to send a file's contents asynchronously, use send_file($filename) instead of delayed, as it will automatically take advantage of any asynchronous capability.

Action Skipping

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 {
    pass if route_parameters->get('word') =~ /^\d+$/;
    "I say a word: " . route_parameters->get('word');
};

get '/say/:number' => sub {
    "I say a number: " . route_parameters->get('number');
};

HOOKS

Hooks are code references (or anonymous subroutines) that are triggered at specific moments during the resolution of a request. They are set up using the hook keyword.

Many of them are provided by Dancer2's core, but plugins and engines can also define their own.

Templates

Error Handling

Refer to Error Hooks for details about the following hooks:

File Rendering

Refer to File Handler for details on the following hooks:

Serializers

HANDLERS

File Handler

Whenever a content is produced out of the parsing of a static file, the Dancer2::Handler::File component is used. This component provides two hooks, before_file_render and after_file_render.

before_file_render hooks are called just before starting to parse the file, the hook receives as its first argument the file path that is going to be processed.

hook before_file_render => sub {
    my $path = shift;
};

after_file_render hooks are called after the file has been parsed and the response content produced. It receives the response object (Dancer2::Core::Response) produced.

hook after_file_render => sub {
   my $response = shift;
};

Auto page

Whenever a page that matches an existing template needs to be served, the Dancer2::Handler::AutoPage component is used.

Writing your own

A route handler is a class that consumes the Dancer2::Core::Role::Handler role. The class must implement a set of methods: methods, regexp and code which will be used to declare the route.

Let's look at Dancer2::Handler::AutoPage for example.

First, the matching methods are get and head:

sub methods { qw(head get) }

Then, the regexp or the path we want to match:

sub regexp { '/:page' }

Anything will be matched by this route, since we want to check if there's a view named with the value of the page token. If not, the route needs to pass, letting the dispatching flow to proceed further.

sub code {
    sub {
        my $app = shift;
        my $prefix = shift;

        my $template = $app->template_engine;
        if ( !defined $template ) {
            $app->response->has_passed(1);
            return;
        }

        my $page       = $app->request->path;
        my $layout_dir = $template->layout_dir;
        if ( $page =~ m{^/\Q$layout_dir\E/} ) {
            $app->response->has_passed(1);
            return;
        }

        # remove leading '/', ensuring paths relative to the view
        $page =~ s{^/}{};
        my $view_path = $template->view_pathname($page);

        if ( ! $template->pathname_exists( $view_path ) ) {
            $app->response->has_passed(1);
            return;
        }

        my $ct = $template->process( $page );
        return ( $app->request->method eq 'GET' ) ? $ct : '';
    };
}

The code method passed the Dancer2::Core::App object which provides access to anything needed to process the request.

A register is then implemented to add the route to the registry and if the auto_page setting is off, it does nothing.

sub register {
    my ($self, $app) = @_;

    return unless $app->config->{auto_page};

    $app->add_route(
        method => $_,
        regexp => $self->regexp,
        code   => $self->code,
    ) for $self->methods;
}

The config parser looks for a route_handlers section and any handler defined there is loaded. Thus, any random handler can be added to your app. For example, the default config file for any Dancer2 application is as follows:

route_handlers:
  File:
    public_dir: /path/to/public
  AutoPage: 1

ERRORS

Error Pages

When an HTTP error occurs (i.e. the action responds with a status code other than 200), this is how Dancer2 determines what page to display.

Execution Errors

When an error occurs during the route execution, Dancer2 will render an error page with the HTTP status code 500.

It's possible either to display the content of the error message or to hide it with a generic error page. This is a choice left to the end-user and can be controlled with the show_stacktrace setting (see above).

Error Hooks

When an error is caught by Dancer2's core, an exception object is built (of the class Dancer2::Core::Error). This class provides a hook to let the user alter the error workflow if needed.

init_error hooks are called whenever an error object is built, the object is passed to the hook.

hook init_error => sub {
    my $error = shift;
    # do something with $error
};

This hook was named before_error_init in Dancer, both names currently are synonyms for backward-compatibility.

before_error hooks are called whenever an error is going to be thrown, it receives the error object as its sole argument.

hook before_error => sub {
    my $error = shift;
    # do something with $error
};

This hook was named before_error_render in Dancer, both names currently are synonyms for backward-compatibility.

after_error hooks are called whenever an error object has been thrown, it receives a Dancer2::Core::Response object as its sole argument.

hook after_error => sub {
    my $response = shift;
};

This hook was named after_error_render in Dancer, both names currently are synonyms for backward-compatibility.

on_route_exception is called when an exception has been caught, at the route level, just before rethrowing it higher. This hook receives a Dancer2::Core::App and the error as arguments.

hook on_route_exception => sub {
  my ($app, $error) = @_;
};

SESSIONS

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.

By default Dancer 2 has Simple sessions enabled. It implements a very simple in-memory session storage. This will be fast and useful for testing, but such sessions will not persist between restarts of your app.

If you'd like to use a different session engine you must declare it in the configuration file.

For example to use YAML file base sessions you need to add the following to your config.yml:

session: YAML

Or, to enable session support from within your code,

set session => 'YAML';

(However, controlling settings is best done from your config file.)

The Dancer2::Session::YAML backend implements a file-based YAML session storage to help with debugging, but shouldn't be used on production systems.

There are other session backends, such as Dancer2::Session::Memcached, which are recommended for production use.

You can then use the session keyword to manipulate the session:

Storing data in the session

Storing data in the session is as easy as:

session varname => 'value';

Retrieving data from the session

Retrieving data from the session is as easy as:

session('varname')

Or, alternatively,

session->read("varname")

Controlling where sessions are stored

For disc-based session backends like Dancer2::Session::YAML, 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.

Changing session ID

If you wish to change the session ID (for example on privilege level change):

my $new_session_id = app->change_session_id

Destroying a session

When you're done with your session, you can destroy it:

app->destroy_session

Sessions and logging in

A common requirement is to check the user is logged in, and, if not, require them to log in before continuing.

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->path !~ m{^/login}) {
        forward '/login', { requested_path => request->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
    # query_parameters->get('requested_path'), so could be put in a hidden field in the form
    template 'login', { path => query_parameters->get('requested_path') };
};

post '/login' => sub {
    # Validate the username and password they supplied
    if (body_parameters->get('user') eq 'bob' && body_parameters->get('pass') eq 'letmein') {
        session user => body_parameters->get('user');
        redirect body_parameters->get('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_value = body_parameters->get('user');
    my $pass_value = body_parameters->get('pass');

    my $user = database->quick_select('users',
        { username => $user_value }
    );
    if (!$user) {
        warning "Failed login for unrecognised user $user_value";
        redirect '/login?failed=1';
    } else {
        if (Crypt::SaltedHash->validate($user->{password}, $pass_value))
        {
            debug "Password correct";
            # Logged in successfully
            session user => $user;
            redirect body_parameters->get('path') || '/';
        } else {
            debug("Login failed - password incorrect for " . $user_value);
            redirect '/login?failed=1';
        }
    }
};

Retrieve complete hash stored in session

Get complete hash stored in session:

my $hash = session;

Writing a session engine

In Dancer 2, a session backend consumes the role Dancer2::Core::Role::SessionFactory.

The following example using the Redis 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 Dancer2::Session::Redis:

package Dancer2::Session::Redis;
use Moo;
with 'Dancer2::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 Dancer2::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, 'Dancer2::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 Dancer2::Core::Session object and is supposed to store it.

sub _flush {
    my ($self, $session) = @_;
    my $json = encode_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.

The Session keyword

Dancer2 maintains two session layers.

The first layer, Dancer2::Core::Session provides a session object which represents the current session. You can read from it as many times as you want, and write to it as many times as you want.

The second layer is the session engine (Dancer2::Session::Simple is one example), which is used in order to implement the reading and writing from the actual storage. This is read only once, when a request comes in (using a cookie whose value is dancer.session by default). At the end of a request, all the data you've written will be flushed to the engine itself, which will do the actual write to the storage (whether it's in a hash in memory, in Memcache, or in a database).

TEMPLATES

Returning plain content is all well and good for examples or trivial apps, but soon you'll want to use templates to maintain separation between your code and your content. Dancer2 makes this easy.

Your route handlers can use the template keyword to render templates.

Views

In Dancer2, a file which holds a template is called a view. Views are located in the appdir/views directory.

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( app->location , '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 install the Template module.

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 = route_parameters->get('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',
        },
    },
};

Layouts

A layout is a special view, located in the layouts directory (inside the views directory) which must have a token named content. That token marks the place where to render the action view. This lets you define a global layout for your actions, and have each individual view contain only specific content. This is a good thing and helps avoid lots of needless duplication of HTML. :)

For example, the 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_render 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.

Encoding

If you use Plack and have a Unicode problem with your Dancer2 application, don't forget to check if you have set your template engine to use Unicode, and set the default charset to 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

Default Template Variables

Every template knows about the following variables, which are provided by Dancer2::Core::Role::Template. Some are similar to the keywords you can use in the Perl part of your Dancer2 application.

STATIC FILES

Static Directory

Static files are served from the ./public directory. You can specify a different location by setting the public_dir option:

set public_dir => path( app->location , 'static' );

When you modify default public_dir you have to set static_handler option.

set static_handler => true;

Note that the public directory name is not included in the URL. A file ./public/css/style.css is made available as http://example.com/css/style.css.

Static File from a Route Handler

It's possible for a route handler to send a static file, as follows:

get '/download/*' => sub {
    my ($file) = splat;

    send_file $file;
};

Or even if you want your index page to be a plain old index.html file, just do:

get '/' => sub {
    send_file '/index.html'
};

FILE UPLOADS

Files are uploaded in Dancer2 using the class Dancer2::Core::Request::Upload. The objects are accessible within the route handlers using the upload keyword:

post '/upload' => sub {
    my $upload     = upload('file_input_name');    # upload object
    $upload->copy_to('Uploads/');
};

CONFIGURATION

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 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').

You can change the running environment when starting your app using the plackup command's --env or --E switch:

plackup -E production bin/app.psgi

Altenatively, you can set the DANCER_ENVIRONMENT environment variable in the shell or in your web server's configuration file.

Typically, you'll want to set the following values in a development config file:

# appdir/environments/development.yml
log: 'debug'
startup_info: 1
show_stacktrace:  1

And in a production one:

# appdir/environments/production.yml
log: 'warning'
startup_info: 0
show_stacktrace:  0

Please note that you are not limited to writing configuration files in YAML. Dancer2 supports any file format that is supported by Config::Any, such as JSON, XML, INI files, and Apache-style config files. See the Dancer2 configuration guide for more information.

Accessing configuration information

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. :)

Settings

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).

Serializers

When writing a webservice, data serialization/deserialization is a common issue to deal with. Dancer2 can automatically handle that for you, via a serializer.

When setting up a serializer, a new behaviour is authorized for any route handler you define: any non-scalar response will be rendered as a serialized string, via the current serializer.

Here is an example of a route handler that will return a hashref:

use Dancer2;
set serializer => 'JSON';

get '/user/:id/' => sub {
    { foo => 42,
      number => 100234,
      list => [qw(one two three)],
    }
};

Dancer2 will render the response via the current serializer.

Hence, with the JSON serializer set, the route handler above would result in a content like the following:

{"number":100234,"foo":42,"list":["one","two","three"]}

If you send a value which is validated serialized data, but is not in the form a key and value pair (such as a serialized string or a JSON array), the data will not be available in params but will be available in request->data.

The following serializers are available, be aware they dynamically depend on Perl modules you may not have on your system.

Importing using Appname

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;

LOGGING

Configuring logging

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).

Logging your own messages

Just call debug, info, warning or error with your message:

debug "This is a debug message from my app.";

TESTING

Using Plack::Test

Plack::Test receives a common web request (using standard HTTP::Request objects), fakes a web server in order to create a proper 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.

Basic Example

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' );

Putting it together

# 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();

Subtests

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 '/:user' => sub {
    my $user = route_parameters->get('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();

Cookies

To handle cookies, which are mostly used for maintaining sessions, the following modules can be used:

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.

Accessing the configuration file

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";

# ...

PACKAGING

Carton

What it does

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:

Setting it up

First set up a new app:

$ dancer2 gen -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.

FatPacker

App::FatPacker (using its command line interface, fatpack) packs dependencies into a single file, allowing you to carry a single file instead of a directory tree.

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 .

MIDDLEWARES

Plack middlewares

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 MyApp;
use Plack::Builder;

builder {
    enable 'Deflater';
    enable 'Session', store => 'File';
    enable 'Debug', panels => [ qw<DBITrace Memory Timer> ];
    MyApp->to_app;
};

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.

Path-based middlewares

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 MyApp;
use Plack::Builder;

my $special_handler = sub { ... };

builder {
    mount '/special' => $special_handler;
    mount '/'        => MyApp->to_app;
};

Removing default middlewares

By default, a Dancer2 app is automatically wrapped with the following middleware

You can configure the setting no_default_middleware to a true value to stop your Dancer2 app being wrapped with these default middleware layers.

# in you Dancer2 app or config.yml
package MyApp;
use Dancer2

set no_default_middleware => true;

This is necessary if you need to add eTag or ContentMD5 headers to HEAD requests, and you are encouraged to manually add those default middleware back into your PSGI stack.

Running on Perl web servers with plackup

A number of Perl web servers supporting PSGI are available on CPAN:

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.

Enabling content compression

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 MyApp;
use Plack::Builder;

builder {
    enable 'Deflater';
    MyApp->to_app;
};

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.

Running multiple apps with Plack::Builder

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->to_app;
    mount '/forum' => OurForum->to_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.

Running from Apache with Plack

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>

PLUGINS

Writing a plugin

See "Writing the plugin" in Dancer2::Plugin for information on how to author a new plugin for Dancer2.

EXPORTS

By default, use Dancer2 exports all the DSL keywords and sets up the webapp under the name of the current package. The following tags control exports and webapp namespace.

When you use Dancer2, you get an import method added into the current package. This will override previously declared import methods from other sources, such as Exporter. Dancer2 applications support the following tags on import:

DSL KEYWORDS

Dancer2 provides you with a DSL (Domain-Specific Language) which makes implementing your web application trivial.

For example, take the following example:

use Dancer2;

get '/hello/:name' => sub {
    my $name = route_parameters->get('name');
};
dance;

get and route_parameters are keywords provided by Dancer2.

See "DSL Keywords manual" in Dancer2::Manual::Keywords for a complete list of keywords provided by Dancer2.

AUTHOR

Dancer Core Developers

COPYRIGHT AND LICENSE

This software is copyright (c) 2023 by Alexis Sukrieh.

This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.