Created
December 3, 2012 12:53
-
-
Save kraih/4194858 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
...much better... ;-)