Advertisement
thomasoniii

Mojo after_static caching gzip

Sep 23rd, 2014
26
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 0.72 KB | None | 0 0
  1. use IO::Compress::Gzip qw(gzip);
  2.  
  3. $self->hook(after_static => sub {
  4.     my $c = shift;
  5.  
  6.     #only gzip if config allows it.
  7.     return unless $c->config->{'gzip_static'};
  8.  
  9.     return unless ($c->req->headers->accept_encoding // '') =~ /gzip/i;
  10.  
  11.     $c->res->headers->append(Vary => 'Accept-Encoding');
  12.  
  13.     # Compress content with gzip
  14.     $c->res->headers->content_encoding('gzip');
  15.  
  16.     if ($c->res->content->asset->can('path')) {
  17.         my $path = $c->res->content->asset->path;
  18.         my $gzpath = "$path.gz";
  19.  
  20.         if (! -e $gzpath || (stat($path))[9] > (stat($gzpath))[9]) {
  21.             gzip $path, $gzpath;
  22.         }
  23.  
  24.         $c->res->content->asset(Mojo::Asset::File->new(path => $gzpath));
  25.     }
  26.  
  27. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement