| 1 | package Plack::Middleware::Chunked; | ||
| 2 | use strict; | ||
| 3 | use parent qw(Plack::Middleware); | ||
| 4 | |||
| 5 | use Plack::Util; | ||
| 6 | |||
| 7 | sub call { | ||
| 8 | my($self, $env) = @_; | ||
| 9 | my $res = $self->app->($env); | ||
| 10 | $self->response_cb($res, sub { | ||
| 11 | my $res = shift; | ||
| 12 | my $h = Plack::Util::headers($res->[1]); | ||
| 13 | if ($env->{'SERVER_PROTOCOL'} ne 'HTTP/1.0' and | ||
| 14 | ! Plack::Util::status_with_no_entity_body($res->[0]) and | ||
| 15 | ! $h->exists('Content-Length') and | ||
| 16 | ! $h->exists('Transfer-Encoding') | ||
| 17 | ) { | ||
| 18 | $h->set('Transfer-Encoding' => 'chunked'); | ||
| 19 | my $done; | ||
| 20 | return sub { | ||
| 21 | my $chunk = shift; | ||
| 22 | return if $done; | ||
| 23 | unless (defined $chunk) { | ||
| 24 | $done = 1; | ||
| 25 | return "0\015\012\015\012"; | ||
| 26 | } | ||
| 27 | return '' unless length $chunk; | ||
| 28 | return sprintf('%x', length $chunk) . "\015\012$chunk\015\012"; | ||
| 29 | }; | ||
| 30 | } | ||
| 31 | }); | ||
| 32 | } | ||
| 33 | |||
| 34 | 1; | ||
| 35 | |||
| 36 | __END__ |