Amon2-Plugin-Web-CpanelJSON
view release on metacpan or search on metacpan
lib/Amon2/Plugin/Web/CpanelJSON.pm view on Meta::CPAN
}
}
$res
};
return $res;
}
}
sub _generate_json_encoder {
my $conf = shift;
my $json = Cpanel::JSON::XS->new;
if (my $json_args = $conf->{json}) {
for my $key (keys %{$json_args}) {
$json->$key($json_args->{$key})
}
}
my $escape_filter = $conf->{json_escape_filter} || {};
my $escape_target = '';
for my $key (keys %{$escape_filter}) {
if ($escape_filter->{$key}) {
$escape_target .= $key
}
}
return sub {
my ($data, $spec) = @_;
if (my $unbless_object = $conf->{unbless_object}) {
if (blessed($data)) {
$data = $unbless_object->($data, $spec);
}
}
my $output = $json->encode($data, $spec);
if ($escape_target && $escape_filter) {
$output =~ s!([$escape_target])!$escape_filter->{$1}!g;
}
return $output;
}
}
sub _generate_req_validator {
my $conf = shift;
return sub {
my ($c) = @_;
# defense from JSON hijacking
if ($conf->{defence_json_hijacking_for_legacy_browser}) {
my $user_agent = $c->req->user_agent || '';
if (
(!$c->req->header('X-Requested-With')) &&
$user_agent =~ /android/i &&
defined $c->req->header('Cookie') &&
($c->req->method||'GET') eq 'GET'
) {
return _error_response($c);
}
}
}
}
sub _error_response {
my $c = shift;
my $res = $c->create_response(403);
$res->content_type('text/plain');
$res->content("invalid JSON request");
$res->content_length(length $res->content);
return $res;
}
1;
__END__
=encoding utf-8
=head1 NAME
Amon2::Plugin::Web::CpanelJSON - Cpanel::JSON::XS plugin
=head1 SYNOPSIS
use Amon2::Lite;
use Cpanel::JSON::XS::Type;
use HTTP::Status qw(:constants);
__PACKAGE__->load_plugins(qw/Web::CpanelJSON/);
use constant HelloWorld => {
message => JSON_TYPE_STRING,
};
get '/' => sub {
my $c = shift;
return $c->render_json(+{ message => 'HELLO!' }, HelloWorld, HTTP_OK);
};
__PACKAGE__->to_app();
=head1 DESCRIPTION
This is a JSON plugin for Amon2.
The differences from Amon2::Plugin::Web::JSON are as follows.
* Cpanel::JSON::XS::Type is available
* HTTP status code can be specified
* Flexible Configurations
=head1 METHODS
=over 4
( run in 1.598 second using v1.01-cache-2.11-cpan-ceb78f64989 )