Skip to content

Instantly share code, notes, and snippets.

@cho45
Created October 6, 2011 15:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cho45/1267700 to your computer and use it in GitHub Desktop.
Save cho45/1267700 to your computer and use it in GitHub Desktop.
#!plackup
use strict;
use warnings;
use Plack::Request;
use JSON::XS;
use XML::LibXML;
use LWP::Simple qw($ua);
my $appid = '';
my $app = sub {
my $req = Plack::Request->new(shift);
my $res = $req->new_response(200);
my $text = $req->param('text');
my $uri = URI->new('http://jlp.yahooapis.jp/KouseiService/V1/kousei');
$uri->query_form(
appid => $appid,
sentence => $text,
);
my $api = $ua->get($uri);
my $xml = $api->content;
my $doc = XML::LibXML->load_xml( string => $xml );
my $xpc = XML::LibXML::XPathContext->new($doc);
$xpc->registerNs('k', 'urn:yahoo:jp:jlp:KouseiService');
my $result = [];
for my $node (@{ $xpc->findnodes('/k:ResultSet/k:Result') }) {
push @$result, +{
start => $xpc->findvalue('k:StartPos', $node) + 0,
length => $xpc->findvalue('k:Length', $node) + 0,
surface => $xpc->findvalue('k:Surface', $node),
word => $xpc->findvalue('k:ShitekiWord', $node),
info => $xpc->findvalue('k:ShitekiInfo', $node),
};
}
my $json = encode_json +{
status => 200,
result => $result,
};
my $callback = $req->param('callback');
if ($callback && $callback =~ /^[a-zA-Z0-9\.\_\[\]]+$/i) {
$res->content_type("text/javascript");
$res->content(sprintf('%s(%s);', $callback, $json));
} else {
$res->content_type("application/json");
$res->content($json);
}
$res->finalize;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment