Created
September 1, 2011 20:31
-
-
Save vti/1187191 to your computer and use it in GitHub Desktop.
metacpan jsonp via roles
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
diff --git a/lib/MetaCPAN/Role/JSONP.pm b/lib/MetaCPAN/Role/JSONP.pm | |
new file mode 100644 | |
index 0000000..61b1ab6 | |
--- /dev/null | |
+++ b/lib/MetaCPAN/Role/JSONP.pm | |
@@ -0,0 +1,37 @@ | |
+package MetaCPAN::Role::JSONP; | |
+use Moose::Role; | |
+use Encode; | |
+ | |
+before _BEGIN => sub { | |
+ my $self = shift; | |
+ my ($c) = @_; | |
+ | |
+ my $jsonp = $c->req->param('callback'); | |
+ if ($jsonp && $jsonp =~ m/^[\w\.\[\]]+$/) { | |
+ | |
+ # We remove callback param so it doesn't go any further. | |
+ # ElasticSearch for example supports JSONP calls too | |
+ $c->req->param('callback', undef); | |
+ | |
+ $c->stash->{jsonp} = $jsonp; | |
+ } | |
+}; | |
+ | |
+after _END => sub { | |
+ my $self = shift; | |
+ my ($c) = @_; | |
+ | |
+ if (my $jsonp = delete $c->stash->{jsonp}) { | |
+ $c->res->content_type('text/javascript'); | |
+ | |
+ my $body = $c->res->output(); | |
+ $body = "$jsonp($body);"; | |
+ $body = decode('UTF-8', $body); # This is JSON, UTF-8 should be enough? | |
+ | |
+ $c->res->output($body); | |
+ } | |
+ | |
+ return 1; | |
+}; | |
+ | |
+1; | |
diff --git a/lib/MetaCPAN/Server/Controller/Author.pm b/lib/MetaCPAN/Server/Controller/Author.pm | |
index 1d9bd27..1bf1b12 100644 | |
--- a/lib/MetaCPAN/Server/Controller/Author.pm | |
+++ b/lib/MetaCPAN/Server/Controller/Author.pm | |
@@ -1,6 +1,7 @@ | |
package MetaCPAN::Server::Controller::Author; | |
use Moose; | |
BEGIN { extends 'MetaCPAN::Server::Controller' } | |
+with 'MetaCPAN::Role::JSONP'; | |
sub index : Chained('/') : PathPart('author') : CaptureArgs(0) { | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment