Compressing CGI output with Perl and Gzip::Faster

This is a simple example program to illustrate the use of gzip, via the Perl module Gzip::Faster, to compress the output of a CGI program. The program tests for the header HTTP_ACCEPT_ENCODING, and if it finds that gzip is a valid output encoding it returns its output compressed in gzip format.

Call this something like compress-test.cgi, mark it as executable, and put it into a directory where it will be served by a web server.

#!/usr/local/bin/perl
use warnings;
use strict;
use Gzip::Faster;

# This variable is set to a true value if it is OK to compress the
# output.

my $gzip_ok;

# Check the environment variable HTTP_ACCEPT_ENCODING for the value
# "gzip".

my $accept_encoding = $ENV{HTTP_ACCEPT_ENCODING};
if ($accept_encoding && $accept_encoding =~ /\bgzip\b/) {
    $gzip_ok = 1;
}

# Print the HTTP header

print "Content-Type: text/html\n";
if ($gzip_ok) {
    print "Content-Encoding: gzip\n";
}
print "\n";

# Create the contents for the default case where compression is not
# possible.

my $stuff = <<EOF;
This is not compressed.
EOF

# The output of the CGI script goes into $output.

my $output = $stuff;

if ($gzip_ok) {

    # Compress if possible. Here we change the message given so that
    # it is possible to tell whether or not the output has been
    # compressed by looking at the web browser.

    $stuff =~ s/not (compressed)/$1/;
    $output = gzip ($stuff);
}

print $output;

exit;

(download)


Copyright © Ben Bullock 2009-2017. All rights reserved. For comments, questions, and corrections, please email Ben Bullock (benkasminbullock@gmail.com). / Privacy / Disclaimer