use CGI; use JSON; use Encode; $CGI::POST_MAX = 1024 * 5; # 5KB my %reply = ( decode('euc-jp',"リンゴ") =>"apple", decode('euc-jp',"ミカン") =>"orange", decode('euc-jp',"バナナ") =>"banana", decode('euc-jp',"パイナップル") =>"pineapple", decode('euc-jp',"スイカ") =>"watermelon" ); my $fmt1 = decode('euc-jp', "%s ? 知らない名前ですね"); my $fmt2 = decode('euc-jp', "それは %s の事ですね!"); my $cgi = CGI->new(); my $json = JSON->new->utf8(0); my $ans; ## ## "POSTDATA"はPOSTメソッド使用時のBODY全体を指しています。 ## "PUTDATA"はPUTメソッド使用時のBODY全体です。 my $postdata = $cgi->param("POSTDATA"); eval { ## JSONデータをパースしてPerlオブジェクトを取り出します。 my $data = $json->decode($postdata); ## $dataのプロパティ q に使用する値が入ってます。 my $q = decode('utf-8', $data->{q}); ## $qの値から送り返すデータをPerlオブジェクトで作ります my $message = sprintf($fmt1, $q); $message = sprintf($fmt2, $reply{$q}) if exists($reply{$q}); $ans = { message => $message, status => 200 }; }; if ($@) { $ans = { message => 'send data broken.', submessage => $@ , status => 500 }; } ## JSON形式のレスポンスを返すためのレスポンスヘッダ print $cgi->header({type=>'application/json', charset=>'utf-8'}); ## PerlオブジェクトをJSON形式にエンコードしています print $json->encode($ans);