The Perl Toolchain Summit needs more sponsors. If your company depends on Perl, please support this very important event.

NAME

Dancer - lightweight yet powerful web application framework

SYNOPSIS

    #!/usr/bin/perl
    use Dancer;

    get '/hello/:name' => sub {
        return "Why, hello there " . params->{name};
    };

    dance;

The above is a basic but functional web app created with Dancer. If you want to see more examples and get up and running quickly, check out the Dancer::Introduction and the Dancer::Cookbook. For examples on deploying your Dancer applications, see Dancer::Deployment.

DESCRIPTION

Dancer is a web application framework designed to be as effortless as possible for the developer, taking care of the boring bits as easily as possible, yet staying out of your way and letting you get on with writing your code.

Dancer aims to provide the simplest way for writing web applications, and offers the flexibility to scale between a very simple lightweight web service consisting of a few lines of code in a single file, all the way up to a more complex fully-fledged web application with session support, templates for views and layouts, etc.

If you don't want to write CGI scripts by hand, and find Catalyst too big or cumbersome for your project, Dancer is what you need.

Dancer has few pre-requisites, so your Dancer webapps will be easy to deploy.

Dancer apps can be used with a an embedded web server (great for easy testing), and can run under PSGI/Plack for easy deployment in a variety of webserver environments.

DISCLAIMER

This documentation describes all the exported symbols of Dancer, if you want to have a quick start guide to discover the framework, you should look at Dancer::Introduction.

If you want to have specific examples of code for real-life problems, see the Dancer::Cookbook.

If you want to see configuration examples of different deployment solutions involving Dancer and Plack, see Dancer::Deployment.

METHODS

after

Add a hook at the after position:

    after sub {
        my $response = shift;
        # do something with request
    };

The anonymous function which is given to after will be executed after having executed a route.

You can define multiple after filters, using the after helper as many times as you wish; each filter will be executed, in the order you added them.

any

Define a route for multiple HTTP methods at once:

    any ['get', 'post'] => '/myaction' => sub {
        # code
    };

Or even, a route handler that would match any HTTP methods:

    any '/myaction' => sub {
        # code
    };

before

Defines a before filter:

    before sub {
        # do something with request, vars or params
    };

The anonymous function which is given to before will be executed before looking for a route handler to handle the request.

You can define multiple before filters, using the before helper as many times as you wish; each filter will be executed, in the order you added them.

before_template

Defines a before_template filter:

    before_template sub {
        # do something with request, vars or params
    };

The anonymous function which is given to before_template will be executed before sending data and tokens to the template.

This filter works as the before and after filter.

cookies

Access cookies values, which returns a hashref of Dancer::Cookie objects:

    get '/some_action' => sub {
        my $cookie = cookies->{name};
        return $cookie->value;
    };

config

Access the configuration of the application:

    get '/appname' => sub {
        return "This is " . config->{appname};
    };

content_type

Set the content-type rendered, for the current route handler:

    get '/cat/:txtfile' => sub {
        content_type 'text/plain';

        # here we can dump the contents of params->{txtfile}
    };

Note that if you want to change the default content-type for every route, you have to change the setting content_type instead.

dance

Alias for the start keyword.

debug

Log a message of debug level

    debug "This is a debug message";

dirname

Returns the dirname of the path given:

    my $dir = dirname($some_path);

error

Log a message of error level:

    error "This is an error message";

false

Constant that returns a false value (0).

from_dumper

Deserialize a Data::Dumper structure

from_json

Deserialize a JSON structure

from_yaml

Deserialize a YAML structure

from_xml

Deserialize a XML structure

get

Define a route for HTTP GET requests to the given path:

    get '/' => sub {
        return "Hello world";
    }

halt

This keyword sets a response object with the content given.

When used as a return value from a filter, this breaks the execution flow and renders the response immediatly.

    before sub { 
        if ($some_condition) {
            return halt("Unauthorized");
        }
    };

    get '/' => sub { 
        "hello there";
    };

headers

Add custom headers to responses:

    get '/send/headers', sub {
        headers 'X-Foo' => 'bar', X-Bar => 'foo';
    }

Add a custom header to response:

    get '/send/header', sub {
        header 'X-My-Header' => 'shazam!';
    }

layout

Syntactic sugar around the layout setting, allows you to set the default layout to use when rendering a view:

    layout 'user';

logger

Syntactic sugar around the logger setting, allows you to set the logger engine to use.

    logger 'console';

load

Load one or more perl scripts in the current application's namespace. Syntactic sugar around Perl's require symbol:

    load 'UserActions.pl', 'AdminActions.pl';

load_app

Load a Dancer package. This method takes care to set the libdir to the curent ./lib directory.

    # if we have lib/Webapp.pm, we can load it like:
    load_app 'Webapp';

Note that a package loaded using load_app must import Dancer with the :syntax option, in order not to change the application directory (which has been previously set for the caller script).

load_plugin

Use this keyword to load plugin in the current namespace. As for load_app, the method takes care to set the libdir to the current ./lib directory.

    package MyWebApp;
    use Dancer;

    load_plugin 'Dancer::Plugin::Database';

mime_type

Returns all the user-defined mime-types when called without parameters. Behaves as a setter/getter if parameters given:

    # get the global hash of user-defined mime-types:
    my $mimes = mime_types;

    # set a mime-type
    mime_types foo => 'text/foo';

    # get a mime-type
    my $m = mime_types 'foo';

params

This method should be called from a route handler. Alias to the Dancer::Request params accessor.

pass

This method should be called from a route handler. This method tells Dancer to pass the processing of the request to the next matching route.

You should always return after calling pass:

    get '/some/route' => sub {
        if (...) {
            # we want to let the next matching route handler process this one
            return pass();
        }
    };

path

Helper to concatenate multiple path together, without worrying about the underlying operating system.

    my $path = path(dirname($0), 'lib', 'File.pm');

post

Define a route for HTTP POST requests to the given URL:

    POST '/' => sub {
        return "Hello world";
    }

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 undef;
    get '/page1' => sub {}; will match /page1

del

Define a route for HTTP DELETE requests to the given URL:

del '/resource' => sub { ... };

options

Define a route for HTTP OPTIONS requests to the given URL:

options '/resource' => sub { ... };

put

Define a route for HTTP PUT requests to the given URL:

put '/resource' => sub { ... };

r

Helper to let you define a route pattern as a regular Perl regexp:

This method is DEPRECATED. Dancer now supports real Perl Regexp objects instead. You should not use r() but qr{} instead:

Don't do this:

    get r('/some/pattern(.*)') => sub { };

But rather this:

    get qr{/some/pattern(.*)} => sub { };

redirect

The redirect action is a helper and shortcut to a common HTTP response code (302). You can either redirect to a complete different site or you can also do it within the application:

    get '/twitter', sub {
            redirect 'http://twitter.com/me';
    };

You can also force Dancer to return a specific 300-ish HTTP response code:

    get '/old/:resource', sub {
        redirect '/new/'.params->{resource}, 301;
    };

request

Return a Dancer::Request object representing the current request.

send_error

Return a HTTP error. By default the HTTP code returned is 500.

    get '/photo/:id' => sub {
        if (...) {
            send_error("Not allowed", 403);
        } else {
           # return content
        }
    }

This will not cause your route handler to return immediately, so be careful that your route handler doesn't then override the error. You can avoid that by saying return send_error(...) instead.

send_file

Lets the current route handler send a file to the client.

    get '/download/:file' => sub {
        send_file(params->{file});
    }

The content-type will be set accordingly, depending on the current mime-types definition (see mime_type if you want to defined your own).

set

Lets you define a setting

    set something => 'value';

setting

Lets you get a value of a given setting

    setting('something'); # 'value'

You can create/update cookies with the set_cookie helper like the following:

    get '/some_action' => sub {
        set_cookie 'name' => 'value',
            'expires' => (time + 3600),
            'domain'  => '.foo.com';
    };

In the example above, only 'name' and 'value' are mandatory.

session

Accessor for session object, providing access to all data stored in the current session engine (if any).

It can also be used as a setter to add new data to the current session engine.

    # getter example
    get '/user' => sub {
        if (session('user')) {
            return "Hello, ".session('user')->name;
        }
    };

    # setter example
    post '/user/login' => sub {
        ...
        if ($logged_in) {
            session user => $user;
        }
        ...
    };

splat

When inside a route handler with a route pattern with wildcards, the splat keyword returns the list of captures made:

    get '/file/*.*' => sub {
        my ($file, $extension) = splat;
        ...
    };

start

Starts the application or the standalone server (depending on the deployment choices).

This keyword should be called at the very end of the script, once all routes are defined. At this point, Dancer takes over control.

status

By default, an action will produce an HTTP 200 OK status code, meaning everything is OK. It's possible to change that with the keyword status :

    get '/download/:file' => {
        if (! -f params->{file}) {
            status 'not_found';
            return "File does not exist, unable to download";
        }
        # serving the file...
    };

In that example, Dancer will notice that the status has changed, and will render the response accordingly.

The status keyword receives either a status code or its name in lower case, with underscores as a separator for blanks.

template

Tells the route handler to build a response with the current template engine:

    get '/' => sub {
        ...
        template 'some_view', { token => 'value'};
    };

The first parameter should be a template available in the views directory, the second one (optional) is a hashref of tokens to interpolate, and the third (again optional) is a hashref of options.

For example, to disable the layout for a specific request:

    get '/' => sub {
        template 'index.tt', {}, { layout => undef };
    };

to_dumper

Serialize a structure with Data::Dumper

to_json

Serialize a structure to JSON

to_yaml

Serialize a structure to YAML

to_xml

Serialize a structure to XML

true

Constant that returns a true value (1).

upload

Dancer provides a common interface to handle file uploads. Any uploaded file is accessible as a Dancer::Request::Upload object. you can access all parsed uploads via the upload keyword, like the following:

    post '/some/route' => sub {
        my $file = upload('file_input_foo');
        # file is a Dancer::Request::Upload object
    };

If you named multiple input of type "file" with the same name, the upload keyword will return an array of Dancer::Request::Upload objects:

    post '/some/route' => sub {
        my ($file1, $file2) = upload('files_input');
        # $file1 and $file2 are Dancer::Request::Upload objects
    };

You can also access the raw hashref of parsed uploads via the current request object:

    post '/some/route' => sub {
        my $all_uploads = request->uploads;
        # $all_uploads->{'file_input_foo'} is a Dancer::Request::Upload object
        # $all_uploads->{'files_input'} is an array ref of Dancer::Request::Upload objects
    };

Note that you can also access the filename of the upload received via the params keyword:

    post '/some/route' => sub {
        # params->{'files_input'} is the filename of the file uploaded
    };

See Dancer::Request::Upload for details about the interface provided.

uri_for

Returns a fully-qualified URI for the given path:

    get '/' => sub {
        redirect uri_for('/path');
        # can be something like: http://localhost:3000/path
    };

captures

If there are named captures in the route Regexp, captures returns a reference to a copy of %+.

Named captures are a feature of Perl 5.10, and are not supported in earlier versions.

    get qr{
        / (?<object> user   | ticket | comment )
        / (?<action> delete | find )
        / (?<id> \d+ )
        /?$
    }x
    , sub {
        my $value_for = captures;
        "i don't want to $$value_for{action} the $$value_for{object} $$value_for{id} !"
    };

var

Setter to define a shared variable between filters and route handlers.

    before sub {
        var foo => 42;
    };

Route handlers and other filters will be able to read that variable with the vars keyword.

vars

Returns the hashref of all shared variables set previously during the filter/route chain.

    get '/path' => sub {
        if (vars->{foo} eq 42) {
            ...
        }
    };

warning

Log a warning message through the current logger engine.

AUTHOR

This module has been written by Alexis Sukrieh <sukria@cpan.org> and others, see the AUTHORS file that comes with this distribution for details.

SOURCE CODE

The source code for this module is hosted on GitHub http://github.com/sukria/Dancer

GETTING HELP / CONTRIBUTING

The Dancer development team can be found on #dancer on irc.perl.org: irc://irc.perl.org/dancer

There is also a Dancer users mailing list available - subscribe at:

http://lists.perldancer.org/cgi-bin/listinfo/dancer-users

DEPENDENCIES

Dancer depends on the following modules:

The following modules are mandatory (Dancer cannot run without them)

HTTP::Server::Simple::PSGI
HTTP::Body
MIME::Types
URI

The following modules are optional

Template : In order to use TT for rendering views
YAML : needed for configuration file support
File::MimeInfo::Simple

LICENSE

This module is free software and is published under the same terms as Perl itself.

SEE ALSO

Main Dancer web site: http://perldancer.org/.

The concept behind this module comes from the Sinatra ruby project, see http://www.sinatrarb.com/ for details.