1#!perl
2# Created by Hauke Daempfling 2018
3use strict;
4use warnings;
5use IO::Compress::Gzip qw/$GzipError Z_PARTIAL_FLUSH/;
6
7our $VERSION = '0.67';
8
9my $app = sub {
10	my $env = shift;
11	die "This app needs a server that supports psgi.streaming"
12		unless $env->{'psgi.streaming'};
13	die "The client did not send the 'Accept-Encoding: gzip' header"
14		unless defined $env->{HTTP_ACCEPT_ENCODING}
15			&& $env->{HTTP_ACCEPT_ENCODING} =~ /\bgzip\b/;
16	# Note some browsers don't correctly support gzip correctly,
17	# see e.g. https://metacpan.org/pod/Plack::Middleware::Deflater
18	# but we're not checking that here (and we don't set the Vary header)
19	return sub {
20		my $respond = shift;
21		my $zipped;
22		my $z = IO::Compress::Gzip->new(\$zipped)
23			or die "IO::Compress::Gzip: $GzipError";
24		my $w = $respond->([ 200, [
25				'Content-Type' => 'text/plain; charset=ascii',
26				'Content-Encoding' => 'gzip',
27			] ]);
28		for (1..10) {
29			$z->print("Hello, it is ".gmtime." GMT\n");
30			$z->flush(Z_PARTIAL_FLUSH);
31			$w->write($zipped) if defined $zipped;
32			$zipped = undef;
33			sleep 1;
34		}
35		$z->print("Goodbye!\n");
36		$z->close;
37		$w->write($zipped) if defined $zipped;
38		$w->close;
39	};
40};
41