Created
May 8, 2017 16:22
-
-
Save jberger/687fff38763e70b6712975f6aea8779c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use Mojo::Base -strict; | |
{ | |
package Mojolicious::Plugin::JSONPretty; | |
use Mojo::Base 'Mojolicious::Plugin'; | |
use JSON::MaybeXS; | |
# stolen from Mojo::JSON::MaybeXS | |
my $JSON = JSON::MaybeXS->new( | |
utf8 => 1, | |
canonical => 1, | |
allow_nonref => 1, | |
allow_unknown => 1, | |
allow_blessed => 1, | |
convert_blessed => 1, | |
pretty => 1, | |
); | |
sub register { | |
my ($plugin, $app, $conf) = @_; | |
$app->renderer->add_handler(json_pretty => sub { | |
my ($renderer, $c, $output, $options) = @_; | |
# Disable automatic encoding | |
delete $options->{encoding}; | |
# Encode data from stash value | |
$$output = $JSON->encode(delete $c->stash->{json_pretty}); | |
# add headers | |
$c->res->headers->content_type('application/json;charset=UTF-8'); | |
}); | |
my $always = $conf->{always} || $app->config->{json_pretty}; | |
$app->hook(before_render => sub { | |
my ($c, $args) = @_; | |
return $args->{handler} = 'json_pretty' | |
if exists $args->{json_pretty} || exists $c->stash->{json_pretty}; | |
return unless $always && (exists $args->{json} || exists $c->stash->{json}); | |
# strongly prevent json default handling, | |
# args wins out but remove json stash value too | |
$args->{json_pretty} = delete $c->stash->{json}; | |
$args->{json_pretty} = delete $args->{json} if $args->{json}; | |
$args->{handler} = 'json_pretty'; | |
}); | |
} | |
} | |
use Mojolicious::Lite; | |
#plugin Config => { | |
#default => { | |
#json_pretty => 1, | |
#}, | |
#}; | |
plugin 'JSONPretty'; | |
#plugin 'JSONPretty', {always => 1}; | |
my $data = {hello => 'world', testing => [1..3]}; | |
any '/' => { json => $data }; | |
any '/pretty' => { json_pretty => $data }; | |
app->start; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment