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
commented
on 3 Dec 2012
oh, didn't spot the nm |
augensalat
commented
on 3 Dec 2012
...much better... ;-) |
Bad for big files, because both, original and compressed file are loaded into RAM.