DRY

Web関連の技術の事、食事/お酒の事、旅行の事など

HTTP::Server::Simple::PSGIで簡易ダウンロードサーバの生成

今更ですが何となく。

単純にAndroidのHttpClient辺りから、ポリッとbinaryファイルのダウンロードに反応してくれるサーバが欲しくって。
何かPSGIでポリサクっと出来ないかな〜と探していたら、HTTP::Server::Simple::PSGIにぶつかってお手軽・簡単でした。


ちなみにあまりセキュリティとか考えてないですが、あしからず。。。


 
use strict;
use warnings;

use Plack::Request;
use HTTP::Server::Simple::PSGI;

use File::Basename;
use Data::Dumper;


my $app = sub
{
my $env = shift;
my $req = Plack::Request->new ($env);

# リクエストパラム"f"で期待するのは、/tmp以下のダウンロードしたいファイルへの相対パス
my $f = $req->param ('f');
if (!defined ($f) || !$f)
{
return [404, [ "Content-Type" => "text/plain" ], [ "Invalid request parameter \"f\"" ]];
}

my $filepath = "/tmp/".$f;
if (!-f $filepath)
{
return [404, [ "Content-Type" => "text/plain" ], [ "No such file or directory." ]];
}

my $filename = basename ($filepath);
local $/;
my $fh = IO::File->new ();
$fh->open ($filepath) or die $!;
return [200,
['Content-Type' => "application/download; name=\"$filename\"\n",
'Content-Disposition' => "attachment; filename=$filename" ],
[$fh->getlines]];
};


my $server = HTTP::Server::Simple::PSGI->new (1971);
$server->app ($app);
$server->run;


# plackup -r --port 1971 -a /tmp/dl.psgi
# http:192.168.72.1:1971/?f=a.dat