In case you want to avoid a 404 error, or handle multiple routes in the same way and you don't feel like configuring all of them, you can set up a default route handler.
The default route handler will handle any request that doesn't get served by any other route.
All you need to do is set up the following route as the last route:
any qr{.*} => sub {
status 'not_found';
template 'special_404', { path => request->path };
};
Then you can set up the template like so:
You tried to reach [% path %], but it is unavailable at the moment.
Please try again or contact us at <[email protected]>.
For simple "static" pages you can simply enable the auto_page
config setting; this means you don't need to declare a route handler for those pages; if a request is for /foo/bar
, Dancer2 will check for a matching view (e.g. /foo/bar.tt
and render it with the default layout etc. if found. For full details, see the documentation for the auto_page setting.
As an AJAX query is just an HTTP query, it's similar to a GET or POST route. You may ask yourself why you may want to use the ajax
keyword (from the Dancer2::Plugin::Ajax plugin) instead of a simple get
.
Let's say you have a path like /user/:user
in your application. You may want to be able to serve this page with a layout and HTML content. But you may also want to be able to call this same url from a javascript query using AJAX.
So, instead of having the following code:
get '/user/:user' => sub {
if (request->is_ajax) {
# create xml, set headers to text/xml, blablabla
header('Content-Type' => 'text/xml');
header('Cache-Control' => 'no-store, no-cache, must-revalidate');
to_xml({...})
}else{
template users => {...}
}
};
you can have
ajax '/user/:user' => sub {
to_xml({...}, RootName => undef);
}
and
get '/user/:user' => sub {
template users => {...}
}
Because it's an AJAX query, you know you need to return XML content, so the content type of the response is set for you.
Let us assume we are building an application that uses a plotting library to generate a graph and expects to get its data, which is in the form of wordcount from an AJAX call.
For the graph, we need the url /data to return a JSON representation of the wordcount data. Dancer infact has a to_json()
function that takes care of the JSON encapsulation.
get '/data' => sub {
open my $fh, '<', $count_file;
my %contestant;
while (<$fh>) {
chomp;
my ( $date, $who, $count ) = split '\s*,\s*';
my $epoch = DateTime::Format::Flexible->parse_datetime($date)->epoch;
my $time = 1000 * $epoch;
$contestant{$who}{$time} = $count;
}
my @json; # data structure that is going to be JSONified
while ( my ( $peep, $data ) = each %contestant ) {
push @json, {
label => $peep,
hoverable => \1, # so that it becomes JavaScript's 'true'
data => [ map { [ $_, $data->{$_} ] }
sort { $a <=> $b }
keys %$data ],
};
}
my $beginning = DateTime::Format::Flexible->parse_datetime( "2010-11-01")->epoch;
my $end = DateTime::Format::Flexible->parse_datetime( "2010-12-01")->epoch;
push @json, {
label => 'de par',
data => [
[$beginning * 1000, 0],
[ DateTime->now->epoch * 1_000,
50_000
* (DateTime->now->epoch - $beginning)
/ ($end - $beginning)
]
],
};
to_json( \@json );
};
For more serious AJAX interaction, there's also Dancer2::Plugin::Ajax that adds an ajax route handler to the mix.
For better maintainability, you may want to separate some of your application components into different packages. Let's say we have a simple web app with an admin section and want to maintain this in a different package:
package myapp;
use Dancer2;
use myapp::admin;
prefix undef;
get '/' => sub {...};
1;
package myapp::admin;
use Dancer2 appname => 'myapp';
prefix '/admin';
get '/' => sub {...};
1;
The following routes will be generated for us:
- get /
- get /admin/
- head /
- head /admin/
By default, a separate application is created for every package that uses Dancer2. The appname
tag is used to collect routes and hooks into a single Dancer2 application. In the above example, appname => 'myapp'
adds the routes from myapp::admin
to the routes of the app myapp
.
When using multiple applications please ensure that your path definitions do not overlap. For example, if using a default route as described above, once a request is matched to the default route then no further routes (or applications) would be reached.
In Dancer2, creating new errors is done by creating a new Dancer2::Core::Error
my $oopsie = Dancer2::Core::Error->new(
status => 418,
message => "This is the Holidays. Tea not acceptable. We want eggnog.",
context => $context,
)
If not given, the status code defaults to a 500, there is no need for a message if we feel taciturn, and while the $context
(which is a Dancer::Core::Context object holding all the pieces of information related to the current request) is needed if we want to take advantage of the templates, we can also do without.
However, to be seen by the end user, we have to populate the Dancer2::Core::Response object with the error's data. This is done via:
$oopsie->throw($response);
Or, if we want to use the response object already present in the $context
(which is usually the case):
$oopsie->throw;
This populates the status code of the response, sets its content, and throws a halt() in the dispatch process.
The error object has quite a few ways to generate its content.
First, it can be explicitly given
my $oopsie = Dancer::Core::Error->new(
content => '<html><body><h1>OMG</h1></body></html>',
);
If the $context
was given, the error will check if there is a template by the name of the status code (so, say you're using Template Toolkit, 418.tt) and will use it to generate the content, passing it the error's $message
, $status
code and $title
(which, if not specified, will be the standard http error definition for the status code).
If there is no template, the error will then look for a static page (to continue with our example, 418.html) in the public/ directory.
And finally, if all of that failed, the error object will fall back on an internal template.
The simplest way to use errors in routes is:
get '/xmas/gift/:gift' => sub {
die "sorry, we're all out of ponies\n"
if param('gift') eq 'pony';
};
The die will be intercepted by Dancer, converted into an error (status code 500, message set to the dying words) and passed to the response.
In the cases where more control is required, send_error()
is the way to go:
get '/glass/eggnog' => sub {
send_error "Sorry, no eggnog here", 418;
};
And if total control is needed:
get '/xmas/wishlist' => sub {
Dancer::Core::Error->new(
response => response(),
status => 406,
message => "nothing but coal for you, I'm afraid",
template => 'naughty/index',
)->throw unless user_was_nice();
...;
};
Writing a form for authentication is simple: we check the user credentials on a request and decide whether to continue or redirect them to a form. The form allows them to submit their username and password and we save that and create a session for them so when they now try the original request, we recognize them and allow them in.
The application is fairly simple. We have a route that needs authentication, we have a route for showing the login page, and we have a route for posting login information and creating a session.
package MyApp;
use Dancer2;
get '/' => sub {
session('user')
or redirect('/login');
template index => {};
};
get '/login' => sub {
template login => {};
};
post '/login' => sub {
my $username = param('username');
my $password = param('password');
my $redir_url = param('redirect_url') || '/login';
$username eq 'john' && $password eq 'correcthorsebatterystaple'
or redirect $redir_url;
session user => $username;
redirect $redir_url;
};
Dancer2::Plugin::Auth::Tiny allows you to abstract away not only the part that checks whether the session exists, but to also generate a redirect with the right path and return URL.
We simply have to define what routes needs a login using Auth::Tiny's needs
keyword.
get '/' => needs login => sub {
template index => {};
};
It creates a proper return URL using uri_for
and the address from which the user arrived.
We can thus decorate all of our private routes to require authentication in this manner. If a user does not have a session, it will automatically forward it to /login, in which we would render a form for the user to send a login request.
Auth::Tiny even provides a new parameter, return_url
, which can be used to send the user back to their original requested path.
Dancer2::Plugin::Passphrase provides a simple passwords-as-objects interface with sane defaults for hashed passwords which you can use in your web application. It uses bcrypt as the default but supports anything the Digest interface does.
Assuming we have the original user-creation form submitting a username and password:
package MyApp;
use Dancer2;
use Dancer2::Plugin::Passphrase;
post '/register' => sub {
my $username = param('username');
my $password = passphrase( param('password') )->generate;
# $password is now a hashed password object
save_user_in_db( $username, $password->rfc2307 );
template registered => { success => 1 };
};
We can now add the POST method for verifying that username and password:
post '/login' => sub {
my $username = param('username');
my $password = param('password');
my $saved_pass = fetch_password_from_db($username);
if ( passphrase($password)->matches($saved_pass) ) {
session user => $username;
redirect param('return_url') || '/';
}
# let's render instead of redirect...
template login => { error => 'Invalid username or password' };
};
Dancer2 already provides a WRAPPER-like ability, which we call a "layout". The reason we don't use Template Toolkit's WRAPPER (which also makes us incompatible with it) is because not all template systems support it. Actually, most don't.
However, you might want to use it, and be able to define META variables and regular Template::Toolkit variables.
These few steps will get you there:
Disable the layout in Dancer2
You can do this by simply commenting (or removing) the
layout
configuration in the config file.Use the Template Toolkit template engine
Change the configuration of the template to Template Toolkit:
# in config.yml template: "template_toolkit"
Tell the Template Toolkit engine which wrapper to use
# in config.yml # ... engines: template: template_toolkit: WRAPPER: layouts/main.tt
Done! Everything will work fine out of the box, including variables and META variables.
You can turn your app into a proper service running in the background using one of the following examples.
Ubic is an extensible perlish service manager. You can use it to start and stop any services, automatically start them on reboots or daemon failures, and implement custom status checks.
A basic PSGI service description (usually in /etc/ubic/service/application
):
use parent qw(Ubic::Service::Plack);
# if your application is not installed in @INC path:
sub start {
my $self = shift;
$ENV{PERL5LIB} = '/path/to/your/application/lib';
$self->SUPER::start(@_);
}
__PACKAGE__->new(
server => 'Starman',
app => '/path/to/your/application/app.psgi',
port => 5000,
user => 'www-data',
);
Run ubic start application
to start the service.
daemontools is a collection of tools for managing UNIX services. You can use it to easily start/restart/stop services.
A basic script to start an application: (in /service/application/run
)
#!/bin/sh
# if your application is not installed in @INC path:
export PERL5LIB='/path/to/your/application/lib'
exec 2>&1 \
/usr/local/bin/plackup -s Starman -a /path/to/your/application/app.psgi -p 5000
Another option would be to run your app stand-alone as described above, but then use a proxy or load balancer to accept incoming requests (on the standard port 80, say) and feed them to your Dancer2 app.
This could be achieved using various software; examples would include:
You could set up a VirtualHost
for your web app, and proxy all requests through to it:
<VirtualHost mywebapp.example.com:80>
ProxyPass / http://localhost:3000/
ProxyPassReverse / http://localhost:3000/
</VirtualHost>
Or, if you want your webapp to share an existing VirtualHost, you could have it under a specified dir:
ProxyPass /mywebapp/ http://localhost:3000/
ProxyPassReverse /mywebapp/ http://localhost:3000/
It is important for you to note that the Apache2 modules mod_proxy
and mod_proxy_http
must be enabled:
$ a2enmod proxy
$ a2enmod proxy_http
It is also important to set permissions for proxying for security purposes, below is an example.
<Proxy *>
Order allow,deny
Allow from all
</Proxy>
perlbal
is a single-threaded event-based server written in Perl supporting HTTP load balancing, web serving, and a mix of the two, available from http://www.danga.com/perlbal/.
It processes hundreds of millions of requests a day just for LiveJournal, Vox and TypePad and dozens of other "Web 2.0" applications.
It can also provide a management interface to let you see various information on requests handled etc.
It could easily be used to handle requests for your Dancer2 apps, too.
It can be easily installed from CPAN:
perl -MCPAN -e 'install Perlbal'
Once installed, you'll need to write a configuration file. See the examples provided with perlbal, but you'll probably want something like:
CREATE POOL my_dancers
POOL my_dancers ADD 10.0.0.10:3030
POOL my_dancers ADD 10.0.0.11:3030
POOL my_dancers ADD 10.0.0.12:3030
POOL my_dancers ADD 10.0.0.13:3030
CREATE SERVICE my_webapp
SET listen = 0.0.0.0:80
SET role = reverse_proxy
SET pool = my_dancers
SET persist_client = on
SET persist_backend = on
SET verify_backend = on
ENABLE my_webapp
balance
is a simple load-balancer from Inlab Software, available from http://www.inlab.de/balance.html.
It could be used simply to hand requests to a standalone Dancer2 app. You could even run several instances of your Dancer2 app, on the same machine or on several machines, and use a machine running balance
to distribute the requests between them, for some serious heavy traffic handling!
To listen on port 80, and send requests to a Dancer2 app on port 3000:
balance http localhost:3000
To listen on a specified IP only on port 80, and distribute requests between multiple Dancer2 apps on multiple other machines:
balance -b 10.0.0.1 80 10.0.0.2:3000 10.0.0.3:3000 10.0.0.4:3000
You can use lighttp's mod_proxy
:
$HTTP["url"] =~ "/application" {
proxy.server = (
"/" => (
"application" => ( "host" => "127.0.0.1", "port" => 3000 )
)
)
}
This configuration will proxy all requests to the /application
path to the path /
on localhost:3000.
with Nginx:
upstream backendurl {
server unix:THE_PATH_OF_YOUR_PLACKUP_SOCKET_HERE.sock;
}
server {
listen 80;
server_name YOUR_HOST_HERE;
access_log /var/log/YOUR_ACCESS_LOG_HERE.log;
error_log /var/log/YOUR_ERROR_LOG_HERE.log info;
root YOUR_ROOT_PROJECT/public;
location / {
try_files $uri @proxy;
access_log off;
expires max;
}
location @proxy {
proxy_set_header Host $http_host;
proxy_set_header X-Forwarded-Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://backendurl;
}
}
You will need plackup to start a worker listening on a socket :
cd YOUR_PROJECT_PATH
sudo -u www plackup -E production -s Starman --workers=2 \
-l THE_PATH_OF_YOUR_PLACKUP_SOCKET_HERE.sock -a bin/app.psgi
A good way to start this is to use daemontools
and place this line with all environments variables in the "run" file.
The warnings
pragma is already used when one loads Dancer2. However, if you really do not want the warnings
pragma (for example, due to an undesired warning about use of undef values), add a no warnings
pragma to the appropriate block in your module or psgi file.
With Dancer2, it's easy to write REST applications. Dancer2 provides helpers to serialize and deserialize for the following data formats:
- JSON
- YAML
- XML
- Data::Dumper
To activate this feature, you only have to set the serializer
setting to the format you require, for instance in your config file:
serializer: JSON
Or directly in your code:
set serializer => 'JSON';
From now, all hashrefs or arrayrefs returned by a route will be serialized to the format you chose, and all data received from POST or PUT requests will be automatically deserialized.
get '/hello/:name' => sub {
# this structure will be returned to the client as
# {"name":"$name"}
return {name => params->{name}};
};
It's possible to let the client choose which serializer to use. For this, use the mutable
serializer, and an appropriate serializer will be chosen from the Content-Type
header.
It's also possible to return a custom error using the send_error keyword. When you don't use a serializer, the send_error
function will take a string as first parameter (the message), and an optional HTTP code. When using a serializer, the message can be a string, an arrayref or a hashref:
get '/hello/:name' => sub {
if (...) {
send_error("you can't do that");
# or
send_error({reason => 'access denied', message => "no"});
}
};
The content of the error will be serialized using the appropriate serializer.
Serializers essentially do two things:
Deserialize incoming requests
When a user makes a request with serialized input, the serializer automatically deserializes it into actual input parameters.
Serialize outgoing responses
When you return a data structure from a route, it will automatically serialize it for you before returning it to the user.
In order to configure a serializer, you just need to pick which format you want for encoding/decoding (from Dancer2::Serializer) and set it up using the serializer
configuration keyword.
It is recommended to explicitly add it in the actual code instead of the configuration file so it doesn't apply automatically to every app that reads the configuration file (unless that's what you want):
package MyApp;
use Dancer2;
set serializer => 'JSON'; # Dancer2::Serializer::JSON
...
Now that we have a serializer set up, we can just return data structures:
get '/' => sub {
return { resources => \%resources };
};
When we return this data structure, it will automatically be serialized into JSON. No other code is necessary.
We also now receive requests in JSON:
post '/:entity/:id' => sub {
my $entity = param('entity');
my $id = param('id');
# input which was sent serialized
my $user = param('user');
...
};
We can now make a serialized request:
$ curl -X POST http://ourdomain/person/16 -d '{"user":"sawyer_x"}'
Serializers are engines. They affect a Dancer Application, which means that once you've set a serializer, all routes within that package will be serialized and deserialized. This is how the feature works.
As suggested above, if you would like to have both, you need to create another application which will not be serialized.
A common usage for this is an API providing serialized endpoints (and receiving serialized requests) and providing rendered pages.
# MyApp.pm
package MyApp;
use Dancer2;
# another useful feature:
set auto_page => 1;
get '/' => sub { template 'index' => {...} };
# MyApp/API.pm
package MyApp::API;
use Dancer2;
set serializer => 'JSON'; # or any other serializer
get '/' => sub { +{ resources => \%resources, ... } };
# user-specific routes, for example
prefix => '/users' => sub {
get '/view' => sub {...};
get '/view/:id' => sub {...};
put '/add' => sub {...}; # automatically deserialized params
};
...
Then those will be mounted together for a single app:
# handler: app.pl:
use MyApp;
use MyApp::API;
use Plack::Builder;
builder {
mount '/' => MyApp->to_app;
mount '/api' => MyApp::API->to_app;
};
This example demonstrates an app that makes a request to a weather API and then displays it dynamically in a web page.
Other than Dancer2 for defining routes, we will use HTTP::Tiny to make the weather API request, JSON to decode it from JSON format, and finally File::Spec to provide a fully-qualified path to our template engine.
use JSON;
use Dancer2;
use HTTP::Tiny;
use File::Spec;
We use the Template::Toolkit template system for this app. Dancer searches for our templates in our views directory, which defaults to views directory in our current directory. Since we want to put our template in our current directory, we will configure that. However, Template::Toolkit does not want us to provide a relative path without configuring it to allow it. This is a security issue. So, we're using File::Spec to create a full path to where we are.
We also unset the default layout, so Dancer won't try to wrap our template with another one. This is a feature in Dancer to allow you to wrap your templates with a layout when your templating system doesn't support it. Since we're not using a layout here, we don't need it.
set template => 'template_toolkit'; # set template engine
set layout => undef; # disable layout
set views => File::Spec->rel2abs('.'); # full path to views
Now, we define our URL:
my $url = 'http://api.openweathermap.org/data/2.5/weather?id=5110629&units=imperial';
We will define a main route which, upon a request, will fetch the information from the weather API, decode it, and then display it to the user.
Route definition:
get '/' => sub {
...
};
Editing the stub of route dispatching code, we start by making the request and decoding it:
# fetch data
my $res = HTTP::Tiny->new->get($url);
# decode request
my $data = decode_json $res->{'content'};
The data is not just a flat hash. It's a deep structure. In this example, we will filter it for only the simple keys in the retrieved data:
my $metrics = { map +(
ref $data->{$_} ? () : ( $_ => $data->{$_} )
), keys %{$data} };
All that is left now is to render it:
template index => { metrics => $metrics };