perldancer

Perl Dancer trailing slash


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?


Solution

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