Skip to content

Instantly share code, notes, and snippets.

@adokoy001
Created October 13, 2015 17:55
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 adokoy001/56a3eb2d9626d77c4376 to your computer and use it in GitHub Desktop.
Save adokoy001/56a3eb2d9626d77c4376 to your computer and use it in GitHub Desktop.
PSGI Plack example with Japanese comments.
use strict;
use warnings;
use Plack::MIME; # mimeタイプ自動判別用
use Data::Dumper;
use File::Slurp; # 効率的な静的ファイル応答
# 静的ファイル置き場
my $public_dir = './public';
# ディレクトリインデックスの指定
my $index_files = ['index.html','index.htm','top.html'];
# psgiアプリ本体
my $app = sub {
my $env = shift; # plackからの環境変数等が格納されたhashref
# PATH_INFO毎に実行するサブルーチンを定義
my $responses = {
'/top' => sub {
return [
200,
[ 'Content-Type' => 'text/plain' ],
[ 'Welcome!' ]
];
},
'/func_test' => sub {
my $ans=0;
for(1 .. 100){ $ans += $_; }
return [
200,
[ 'Content-Type' => 'text/plain' ],
[ $ans ]
];
},
'/dump_test' => sub {
return [
200,
[ 'Content-Type' => 'text/plain' ],
[ Dumper $env ]
];
},
};
# 404 Not Foundレスポンス
my $not_found = [
404,
['Content-Type' => 'text/plain'],
['404 Not found']
];
# mime type
my $mime = 'application/octet-stream'; # 不明時のデフォルト
if($env->{PATH_INFO} =~ /(\.[^\.]+?)$/i){
my $extension = $1;
$mime = Plack::MIME->mime_type($extension);
}
# PATH_INFOから処理を振り分け
if(defined($responses->{$env->{PATH_INFO}})){
# $responsesに定義済みの場合に実行
return $responses->{$env->{PATH_INFO}}->();
}elsif(-f $public_dir.$env->{PATH_INFO}){
# 静的ファイルが存在する場合に実行
return [
200,
['Content-Type' => $mime],
[read_file($public_dir.$env->{PATH_INFO})],
];
}else{
# ファイル指定されていない場合はディレクトリインデックスをサーチ
foreach my $index_file (@$index_files){
if(-f $public_dir.$env->{PATH_INFO}.$index_file){
if($index_file =~ /(\.[^\.]+?)$/i){
my $extension = $1;
$mime = Plack::MIME->mime_type($extension);
}
return [
200,
['Content-Type' => $mime],
[read_file($public_dir.$env->{PATH_INFO}.$index_file)],
];
}
}
# 最終的に見つからなかった場合は 404 Not Found
return $not_found;
}
};
return $app;
@adokoy001
Copy link
Author

$ plackup plack_psgi_example.pl

@adokoy001
Copy link
Author

Starmanでデーモン化

$ starman --workers 50 --max-requests 200 --port=5000 --daemonize --pid=starman.pid -preload-app -a plack_psgi_example.pl

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment