Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Dancer: Type-checking for the route parameters

  • Int

Dancer allows us to use type-constraints to limit what values we accept in a route. For example we can tell it that the value must be an integer.

If the request does not match the expected type then that route does not match. If none of the routes match then we get a "404 Not Found" error as expected.

package App;
use Dancer2;

get '/' => sub {
    return q{
        <a href="/user/1">One</a><br>
        <a href="/user/2">Two</a><br>
        <a href="/user/foobar">foobar</a><br>
        <a href="/user">user</a><br>
        <a href="/user/">user/</a><br>
        <a href="/user/a/b">a/b</a><br>
        <a href="/user/-1">-1</a><br>
        <a href="/user/1.1">1.1</a><br>
    };
};

get '/user/:id[Int]' => sub {
    my $id = route_parameters->get('id');
    return $id;
};

App->to_app;