2009年12月8日:サンプルコードを現在のバージョンで動作するよう修正しました。
一行掲示板を移植してみよう
連載の1回目では,Mojoのスタンドアロンサーバを使って簡単な画面を表示してみました。今回は簡単なCGIをMojoに移植しながら,リクエストの扱い方やテストの仕方を見ていきましょう。まずはこれから移植していくCGIのソースを掲載します。あきらかに穴だらけのものですが,そこはひとまず目をつむってください。
#!/usr/bin/perl
use strict;
use warnings;
use CGI;
my $q = CGI->new;
my $file = 'data.txt';
unless (-f $file) {
open my $fh, '>', $file or die $!;
close $fh;
}
if ($q->param('text')) {
open my $fh, '>>', $file or die $!;
print $fh $q->param('text'), "\n";
close $fh;
}
open my $fh, '<', $file or die $!;
my @lines = <$fh>;
close $fh;
print "Status: 200 OK\n";
print "Content-Type: text/html; charset=utf-8\n\n";
print <<"END";
<html><head><title>Simple BBS</title></head><body>
<form method="POST"><input type="text" name="text"></form>
@{[ map{ "<p>$_</p>" } @lines ]}
</body></html>
END
最後のヒアドキュメントのなかにPerlの式を埋め込むテクニックはあまりなじみがないものかもしれません。詳しくは竹迫良範さんがJPerl Advent Calendar 2008に寄稿された記事(※1)をご覧ください。
書き直すのはリクエストとレスポンスだけ
さて,これをそのままMojoで書き直してみます。
まずは連載1回目と同じく,Mojoをインストールしたディレクトリに新しいひな形を用意しましょう。
> perl script/mojo generate app SimpleBBS > cd simple_bbs
続いて,lib/SimpleBBS.pmの中身をこう書き換えます。
package SimpleBBS;
use strict;
use warnings;
use base 'Mojo';
sub handler {
my ($self, $tx) = @_;
my $file = 'data.txt';
unless (-f $file) {
open my $fh, '>', $file or die $!;
close $fh;
}
if ($tx->req->param('text')) {
open my $fh, '>>', $file or die $!;
print $fh $tx->req->param('text'), "\n";
close $fh;
}
open my $fh, '<', $file or die $!;
my @lines = <$fh>;
close $fh;
$tx->res->code(200);
$tx->res->headers->content_type('text/html; charset=utf-8');
$tx->res->body(<<"END");
<html><head><title>Simple BBS</title></head><body>
<form method="POST"><input type="text" name="text"></form>
@{[ map{ "<p>$_</p>" } @lines ]}
</body></html>
END
return $tx;
}
1;
連載第1回でも説明した通り,全体がhandlerというサブルーチンの中に記述されていることを除けば,変わったのはCGIオブジェクトのかわりに$tx->reqからアクセスできるMojoのリクエストオブジェクトが使われていることと,出力部分が$tx->resからアクセスできるレスポンスオブジェクトに格納されていることだけです。簡単ですね?

