public
Created

  • Download Gist
kousei.psgi
Perl
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
#!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;
};

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.