Skip to content

Instantly share code, notes, and snippets.

@choplin
Created July 3, 2012 07:46
Show Gist options
  • Save choplin/3038327 to your computer and use it in GitHub Desktop.
Save choplin/3038327 to your computer and use it in GitHub Desktop.
JSONP Proxy with Mojolicious::Lite
#!/usr/bin/perl
use strict;
use warnings;
use utf8;
use feature ':5.10';
use Encode;
use Mojolicious::Lite;
use XML::Simple;
use JSON::Any;
my $ua = Mojo::UserAgent->new;
get '/' => sub{ shift->render(text => 'ok') };
get '/:type' => sub{
my $self = shift;
my $type = $self->param('type');
my $uri = $self->param('uri');
my $callback = $self->param('callback');
my $res = $ua->get($uri)->res;
my $json = to_json($res, $type, $callback);
if($callback){
$self->res->headers->content_type('application/javascript; charset=UTF-8;');
}else{
$self->res->headers->content_type('application/json; charset=UTF-8;');
}
$self->render_data(encode('utf-8', $json));
};
sub to_json {
my $res = shift;
my $type = shift;
my $callback = shift;
my $obj = to_obj($res->body, $type);
my $j = JSON::Any->new(utf8 => 1);
my $ret = $callback ? $callback . '(' . $j->encode($obj) . ')' : $j->encode($obj);
return $ret;
}
sub to_obj{
my $txt = shift;
my $type = shift;
my $ret;
given ($type){
when ('xml') {
$ret = XMLin(decode('utf-8', $txt));
}
default {
$ret = '';
}
}
return $ret;
}
app->start;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment