D-7 <altijd in beweging>

Day to day life of a Perl/Go/C/C++/whatever hacker. May include anything from tech, food, and family.

タグ:CGI

前のエントリ書いたら宮川さんにオススメ方法を教えてもらった

http://twitter.com/miyagawa/status/10271128928
plackup \
      -L Shotgun
      -MPlack::App::WrapCGI
      -e 'Plack::App::WrapCGI->new(script => "/path/to/cgiscript.cgi")'

だそうです!これなら全ての要件を満たせるもよう!そしてapp.psgiを作る必要ありません。

今これやってみて一つだけ問題点。多分POD入りのCGIは動かない。それと、__DATA__は見てくれるけど、__END__があると動かない。__END__さっき簡単なパッチのpull requestを送っておきました!

なお、-L Shotgunを使うと CGIファイルの中身は実行時までコンパイルされないのでご注意(つまり、plackup -rもいらないってことですね)
    このエントリーをはてなブックマークに追加 mixiチェック

ちょっと案件で簡単なCGIスクリプトをを開発することになった。StarmanとかTwiggyでほとんど全て書いているのに今更CGIとかそういう突っ込みはとりあえずおいておいて・・・環境を作るのも面倒くさいし、簡単にサーバーを立ち上げたり落としたりしたい。

そこでPlackです!

追記:その後もらったコメントによると、こちらのほうがよさそうです







具体的にはplackupとCGI::Emulate::PSGIを使います。

何も考えずにとりあえず開発したいので、以下のようにapp.psgiにコードを書いていく。
use strict;
use CGI::Emulate::PSGI;
return CGI::Emulate::PSGI->handler(sub {
    CGI::initialize_globals(); # 重要
# ここから
#!/usr/bin/env perl
use strict;
use warnings;
use CGI;
use CGI::Carp qw(fatalsToBrowser);

sub main {
    my $q = CGI->new();
    ....
}

main();

# ここまでがCGIのコード
});
あとで本当に単純にコピペしたいのでshebangもそのまま書いちゃうし、インデントもその部分だけファイルに書いたかのように記述していっちゃいます。

これを以下のように-rオプションをつけて起動。app.psgiのCGIコードに変更を加える度にサーバーも再起動して新しいコードを適用してくれる。
plackup -r -a app.psgi


これはいいわー。
    このエントリーをはてなブックマークに追加 mixiチェック

某所での会話:
13:14 <#perl6> t****: y'know, one thing that got me into Ruby was that the CGI library would auto-detect that I was testing it in a browser and take arguments as if I was working in a browser. Made troubleshooting a breeze... 13:14 <#perl6> t****: I mean, testing from the command line... 13:15 <#perl6> t****: I always wished the perl CGI module would do that... 13:16 <#perl6> P*******: eh? 13:17 <#perl6> t****: When you write a ruby cgi program, and run it from the command line, it detects that you are in a command line and allows you to input stuff that it would normally get from the URL string. 13:17 <#perl6> t****: Maybe there is a way to do this with the perl cgi module, but I never learned how. 13:17 <#perl6> P*******: perl's CGI module has always done that. 13:18 <#perl6> P*******: you simply pass name=val on the command line 13:18 <#perl6> P*******: (or you could set some environment variables) 13:18 <#perl6> t****: hm... Wish I had known that then...
ええええええええええ。この機能ってすごい有名だと思ってた。
普通にCGI.pmのスクリプトはコマンドラインから実行できるお>< デバッグとかにはとても便利です!
#!/usr/bin/perl use strict; use CGI; my $q = CGI->new(); print $q->header(-content_type => 'text/plain', -charset => 'utf-8'), "Hello, ", $q->param('name') || "NoName", "!\n"
こんなスクリプトを、以下のように実行すると、"Hello, lestrrat!"と本文に表示されます
% perl test.cgi name=lestrrat Content-Type: text/plain; charset=utf-8 Hello, lestrrat!
簡単!・・・まぁ、最近は生CGIでなんか書くってのもなくなってきたけどね
    このエントリーをはてなブックマークに追加 mixiチェック

このページのトップヘ