Skip to content

Instantly share code, notes, and snippets.

@kraih
Created December 3, 2012 12:53
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kraih/4194858 to your computer and use it in GitHub Desktop.
Save kraih/4194858 to your computer and use it in GitHub Desktop.
package Mojolicious::Plugin::GZip;
use Mojo::Base 'Mojolicious::Plugin';
use IO::Compress::Gzip 'gzip';
# Just set "gzip => 1" in the stash and it will try to compress your content
sub register {
my ($self, $app) = @_;
$app->hook(
after_dispatch => sub {
my $self = shift;
# Check if GZip compression is desirable
return unless $self->stash->{gzip};
return unless ($self->req->headers->accept_encoding // '') =~ /gzip/i;
my $res = $self->res;
my $asset = $res->content->asset;
return if $asset->is_file || !$asset->size;
return if $asset->start_range || $asset->end_range;
# Compress content
gzip \(my $dummy = $asset->slurp), \my $compressed;
$res->body($compressed);
$res->headers->content_encoding('gzip');
}
);
}
1;
@augensalat
Copy link

Bad for big files, because both, original and compressed file are loaded into RAM.

@augensalat
Copy link

oh, didn't spot the
return unless !$asset->is_file
so it's probably only for small files anyway

nm

@augensalat
Copy link

...much better... ;-)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment