| | 8 | our $ConformToRFC4627 = 0; |
| | 9 | our $ENCODING = 'utf-8'; |
| | 10 | |
| | 11 | sub import { |
| | 12 | my $pkg = caller(0); |
| | 13 | |
| | 14 | no strict 'refs'; ## no critic. |
| | 15 | *{"$pkg\::output_json_xs"} = \&_output_json_xs; |
| | 16 | } |
| | 17 | |
| | 18 | sub _output_json_xs { |
| | 19 | my ($self, $src) = @_; |
| | 20 | |
| | 21 | my $content_type = |
| | 22 | ( $self->debug_level && $self->r->param('debug') ) |
| | 23 | ? "text/plain; charset=$ENCODING" |
| | 24 | : _content_type($self, $ENCODING ); |
| | 25 | |
| | 26 | my $json = encode_json($src); |
| | 27 | my $output = _add_callback($self, _validate_callback_param($self, ($self->r->param('callback') || '')), $json ); |
| | 28 | $self->r->content_type($content_type); |
| | 29 | $self->set_content_length(length $output); |
| | 30 | $self->send_http_header; |
| | 31 | $self->r->print($output); |
| | 32 | $self->invoke_hook('AFTER_OUTPUT'); |
| | 33 | $self->finished(1); |
| | 34 | } |
| | 35 | |
| | 36 | sub _content_type { |
| | 37 | my ($self, $encoding) = @_; |
| | 38 | |
| | 39 | my $user_agent = $self->r->header_in('User-Agent'); |
| | 40 | |
| | 41 | if ( $ConformToRFC4627 ) { |
| | 42 | return "application/json; charset=$encoding"; |
| | 43 | } elsif (($user_agent || '') =~ /Opera/) { |
| | 44 | return "application/x-javascript; charset=$encoding"; |
| | 45 | } else { |
| | 46 | return "application/javascript; charset=$encoding"; |
| | 47 | } |
| | 48 | } |
| | 49 | |
| | 50 | sub _add_callback { |
| | 51 | my ($self, $cb, $json) = @_; |
| | 52 | |
| | 53 | my $output; |
| | 54 | $output .= "$cb(" if $cb; |
| | 55 | $output .= $json; |
| | 56 | $output .= ");" if $cb; |
| | 57 | |
| | 58 | return $output; |
| | 59 | } |
| | 60 | |
| | 61 | sub _validate_callback_param { |
| | 62 | my ($self, $param) = @_; |
| | 63 | return ( $param =~ /^[a-zA-Z0-9\.\_\[\]]+$/ ) ? $param : undef; |
| | 64 | } |
| 22 | | Sledge::Plugin::JSON::XS is |
| | 87 | Sledge::Plugin::JSON::XS is JSON::XS wrapper for Sledge. |
| | 88 | |
| | 89 | Sledge::Plugin::JSON is wrapper for JSON::Syck. but this module uses JSON::XS. |
| | 90 | |
| | 91 | =head1 CODE COVERAGE |
| | 92 | |
| | 93 | ---------------------------- ------ ------ ------ ------ ------ ------ ------ |
| | 94 | File stmt bran cond sub pod time total |
| | 95 | ---------------------------- ------ ------ ------ ------ ------ ------ ------ |
| | 96 | .../Sledge/Plugin/JSON/XS.pm 100.0 100.0 100.0 100.0 n/a 100.0 100.0 |
| | 97 | Total 100.0 100.0 100.0 100.0 n/a 100.0 100.0 |
| | 98 | ---------------------------- ------ ------ ------ ------ ------ ------ ------ |