tokuhirom's Blog

validate content-length with plack

http://github.com/tokuhirom/p5-plack-middleware-validatecontentlength
I wrote broken webapp, it outputs invalid content-length. Then, I want validator :P

package Plack::Middleware::ValidateContentLength;
use strict;
use warnings;
use parent qw/Plack::Middleware/;
use Plack::Util qw//;

sub call {
    my ( $self, $env ) = @_;

    my $res = $self->app->($env);

    my $header_length = Plack::Util::header_get($res->[1], 'Content-Length');
    if ($header_length) {
        my $body_length = Plack::Util::content_length($res->[2]);
        if ($header_length != $body_length) {
            print STDERR "INVALID CONTENT LENGTH: header: $header_length, body: $body_length, $env->{PATH_INFO}\n";
            return [500, [], ['Content Length Error']];
        }
    }

    return $res;
}

1;
__END__

=head1 SYNOPSIS

    plackup -e 'enable "ValidateContentLength"' -e '[200, ["Content-Length" => 3], ["NOT OK"]]'

(I will not release this middleware :-) This is just quick hack. )