画像回転 Webアプリ

Webアプリというものがよくわかっていないのと Plackを使ってみたいという
ので、作ってみた。少し知識が広がった気がした.

コード

#!/usr/bin/env perl
use strict;
use warnings;

use utf8;
use Encode;
use File::Temp;

use Plack;
use Plack::Builder;
use Plack::Request;
use Plack::MIME;

my $data = do {
    local $/;
    encode_utf8(<DATA>);
};

my $app_index = sub {
    my $env = shift;
    return [200, [ 'Content-Type' => 'text/html' ], [ $data ]];
};

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

    my $angle = $req->body_parameters->{'angle'};
    unless ($angle =~ m{\d+}) {
        return [403, [ 'Content-Type' => 'text/plain' ], [ "Invalid angle: $angle" ] ];
    }

    my (undef, $filename) = File::Temp::tempfile();
    my @cmd = ('convert', '-rotate', $angle, "gnu.png", $filename);
    my $status = system @cmd;
    die "Can't exec @cmd" if $status != 0;
    open my $fh, "<", $filename or die "Can't open file: $filename";
    return [200, [ 'Content-Type' => Plack::MIME->mime_type(".png")], $fh];
};

builder {
    enable "Plack::Middleware::ContentLength";
    enable "Plack::Middleware::Static",
        path => qr{\.png$}, root => './';

    mount "/" => $app_index;
    mount "/convert"  => $app_convert;
};

__DATA__
<!DOCTYPE html>
<html lang="ja">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta http-equiv="Content-Style-Type" content="text/css" />
<title>Image Converter</title>
</head>
<body>
<h1>画像回転</h1>
 <form action="/convert" method="POST" enctype="multipart/form-data">
   <input type="text" name="angle" />度
   <br />
   <input type="submit" name="convert" value="回転します" />
 </form>
 <img src="gnu.png"/>
</body>
</html>

実行

  % plackup app.psgi
  % firefox http://localhost:5000/

結果

がこんな感じに

次は WAFにチャレンジしてみることにします。