Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl Dancer trailing slash

Tags:

perl

dancer

Using the Perl web application framework Dancer, I am having some problems with trailing slashes in the URL matching.

Say for example, I want to match the following URL, with an optional Id parameter:

get '/users/:id?' => sub
{
    #Do something
}

Both /users/morgan and /users/ match. Though /users will not. Which does not seem very uniform. Since I would prefer, only matching the URL:s without the trailing slash: /users/morgan and /users. How would I achieve that?

like image 359
Morgan Bengtsson Avatar asked Feb 18 '13 10:02

Morgan Bengtsson


3 Answers

Another approach is to use a named sub - all the examples of Dancer code tend to use anonymous subs, but there's nothing that says it has to be anonymous.

get '/users' => \&show_users;
get '/users/:id' => \&show_users;

sub show_users
{
    #Do something
}

Note that, due to the way Dancer does the route matching, this is order-dependent and, in my experience, I've had to list the routes with fewer elements first.

like image 115
Dave Sherohman Avatar answered Nov 13 '22 10:11

Dave Sherohman


id will contains everything from /user/ on until an optional slash.

get qr{^/users/?(?<id>[^/]+)?$} => sub {
  my $captures = captures;
  if ( defined $captures->{id} ) {
    return sprintf 'the id is: %s', $captures->{id};
  }
  else {
    return 'global user page'
  }
};
like image 37
burnersk Avatar answered Nov 13 '22 09:11

burnersk


I know this is an old question, but I've recently solved this problem by using a Plack middleware. There are two of them you can choose from depending on whether you prefer URLs with trailing slashes or not:

  • Plack::Middleware::TrailingSlash
  • Plack::Middleware::TrailingSlashKiller

Using any of the middleware above should greatly simplify your core Dancer application code and unit tests since you do not need to handle both cases.

In addition, as mentioned by Dave Sherohman, you should definitely arrange your routes with the fewer elements first in order to match those first, especially if you use the TrailingSlash middleware to force trailing slashes.

like image 2
seav Avatar answered Nov 13 '22 10:11

seav