Amon2
view release on metacpan or search on metacpan
lib/Amon2/Web/Dispatcher/RouterBoom.pm view on Meta::CPAN
# any( '/path', sub { })
for my $method (qw(get post put delete_ any)) {
*{"${caller}::${method}"} = sub {
my ($path, $dest) = @_;
my %dest;
if (ref $dest eq 'CODE') {
$dest{code} = $dest;
} else {
my ($controller, $method) = split('#', $dest);
$dest{class} = $base ? "${base}::${controller}" : $controller;
$dest{method} = $method if defined $method;
}
my $http_method;
if ($method eq 'get') {
$http_method = ['GET','HEAD'];
} elsif ($method eq 'post') {
$http_method = 'POST';
} elsif ($method eq 'put') {
$http_method = 'PUT';
} elsif ($method eq 'delete_') {
$http_method = 'DELETE';
}
$router->add($http_method, $path, \%dest);
};
}
# class methods
*{"${caller}::router"} = sub { $router };
*{"${caller}::dispatch"} = sub {
my ($class, $c) = @_;
my $env = $c->request->env;
if (my ($dest, $captured, $method_not_allowed) = $class->router->match($env->{REQUEST_METHOD}, $env->{PATH_INFO})) {
if ($method_not_allowed) {
return $c->res_405();
}
my $res = eval {
if ($dest->{code}) {
return $dest->{code}->($c, $captured);
} else {
my $method = $dest->{method};
$c->{args} = $captured;
return $dest->{class}->$method($c, $captured);
}
};
if ($@) {
if ($class->can('handle_exception')) {
return $class->handle_exception($c, $@);
} else {
print STDERR "$env->{REQUEST_METHOD} $env->{PATH_INFO} [$env->{HTTP_USER_AGENT}]: $@";
return $c->res_500();
}
}
return $res;
} else {
return $c->res_404();
}
};
}
1;
__END__
=head1 NAME
Amon2::Web::Dispatcher::RouterBoom - Router::Boom bindings
=head1 SYNOPSIS
package MyApp2::Web::Dispatcher;
use Amon2::Web::Dispatcher::RouterBoom;
use MyApp::Web::C::Foo;
base 'MyApp::Web::C';
get '/' => 'Foo#bar';
1;
=head1 DESCRIPTION
This is a router class for Amon2. It's based on Router::Boom.
=head1 DSL FUNCTIONS
=over 4
=item C<< get($path:Str, $destnation:Str) >>
=item C<< post($path:Str, $destnation:Str) >>
=item C<< put($path:Str, $destnation:Str) >>
=item C<< delete_($path:Str, $destnation:Str) >>
=item C<< any($path:Str, $destnation:Str) >>
get '/' => 'Root#index';
get '/:user' => 'User#show';
any '/:user/update' => 'User#update';
post '/:user/blog/post' => 'Blog#post';
put '/:user/blog/put' => 'Blog#put';
delete_ '/:user/blog/:id' => 'Blog#remove';
Add routes by DSL. First argument is the path pattern in Path::Boom rules.
Second argument is the destination method path.
Destination method pass is C<${class}#${method}> form.
The path declared with get() accepts GET and HEAD.
The path declared with post() accepts POST method.
The path declared with put() accepts PUT method.
The path declared with delete_() accepts DELETE method.
The path declared with any() accepts any methods.
( run in 2.993 seconds using v1.01-cache-2.11-cpan-39bf76dae61 )