3

I need to create an HTTP::Response with compressed data. How do I go about making the content gzipped? Do I just add the appropriate headers and compress it myself using Compress::Zlib? Or does any of the LWP modules provide a method for handling this?

mrburns
  • 453
  • 1
  • 8
  • 17
  • [This perlmonks article](http://www.perlmonks.org/?node=858560) might be helpful. – maerics Jul 28 '11 at 23:43
  • See this question: http://stackoverflow.com/questions/1285305/how-can-i-accept-gzip-compressed-content-using-lwpuseragent – Leon Timmermans Jul 29 '11 at 10:20
  • These are about downloading gzipped content. My question is about serving gzipped content through my perl webserver. I have the content as say "abc 12345"; I need to send a gzipped version of it as an HTTP::Response to the client/browser. – mrburns Jul 30 '11 at 21:23

1 Answers1

2

Is this what you need? You gzip the data, set the Content-encoding header, and send it off.

use strict;
use warnings;

use HTTP::Response;
use IO::Compress::Gzip qw(gzip);

my $data = q(My cat's name is Buster);

my $gzipped_data;
my $gzip = gzip \$data => \$gzipped_data;
print STDERR $gzipped_data;

my $response = HTTP::Response->new;

$response->code( 200 );
$response->header( 'Content-type'     => 'text/plain' );
$response->header( 'Content-encoding' => 'gzip' );
$response->header( 'Content-length'   => length $gzipped_data );

$response->content( $gzipped_data );

print $response->as_string;
brian d foy
  • 129,424
  • 31
  • 207
  • 592
  • Thanks for your answer but for some reason the browser is not able to decompress the gzip content. When debugging in Fiddler, I receive the error "The content could not be decompressed. The magic number in the GZip header is not correct. Make sure you are passing in a GZip stream". Any thoughts as to why this is? – HBCondo Dec 04 '19 at 09:44
  • @HBCondo - you'll have to ask another question and show your code. – brian d foy Dec 04 '19 at 18:55