File Coverage

blib/lib/Mojolicious/Plugin/Gzip.pm
Criterion Covered Total %
statement 36 36 100.0
branch 15 16 93.7
condition 23 26 88.4
subroutine 5 5 100.0
pod 1 1 100.0
total 80 84 95.2


line stmt bran cond sub pod time code
1             package Mojolicious::Plugin::Gzip;
2 4     4   24026 use Mojo::Base 'Mojolicious::Plugin';
  4         9  
  4         29  
3 4     4   916 use Mojo::Util qw/gzip/;
  4         8  
  4         205  
4 4     4   27 use Scalar::Util qw/reftype/;
  4         8  
  4         2118  
5              
6             our $VERSION = '0.04';
7              
8             sub register {
9 18     18 1 11714 my (undef, $app, $config) = @_;
10              
11 18         27 my $min_size;
12 18 50       44 if (defined $config) {
13 18 100       80 die 'config must be a hash reference'
14             unless reftype($config) eq 'HASH';
15 17 100       49 if (keys %$config) {
16 12   100     35 $min_size = delete $config->{min_size} // '';
17 12 100       40 die 'invalid key passed to Mojolicious::Plugin::Gzip (only min_size is allowed)'
18             if keys %$config;
19 10 100 100     94 die 'min_size must be a positive integer'
20             unless $min_size =~ /^\d+$/ and $min_size > 0;
21             }
22             }
23 9   100     46 $min_size //= 860;
24              
25             $app->hook(after_dispatch => sub {
26 32     32   324974 my ($c) = @_;
27 32         95 my $req = $c->req;
28 32         314 my $res = $c->res;
29              
30 32   50     292 my $accept_encoding = $req->headers->accept_encoding // '';
31 32         589 my $body = $res->body;
32 32   50     543 my $body_size = $res->body_size // 0;
33              
34 32 100 100     862 return unless $accept_encoding =~ /gzip/i
      100        
      100        
35             and $body_size >= $min_size
36             and $res->code == 200
37             and not $res->headers->content_encoding;
38              
39 19 100       373 if (my $etag = $res->headers->etag) {
40 10 100 100     218 if (length $etag > 2 and substr($etag, 0, 1) eq '"' and substr($etag, -1, 1) eq '"') {
      66        
41 5         25 $etag = substr($etag, 1, length($etag) - 2);
42             } else {
43 5         16 $app->log->warn("Found either empty ETag or ETag not surrounded by quotes: '$etag'");
44             }
45              
46 10         81 $res->headers->etag(qq{"$etag-gzip"});
47             }
48              
49 19         292 my $zipped_body = gzip $body;
50 19         34552 $res->body($zipped_body);
51 19         863 $res->headers->content_length(length $zipped_body);
52 19         273 $res->headers->append(Vary => 'Accept-Encoding');
53 19         781 $res->headers->content_encoding('gzip');
54 9         92 });
55             }
56              
57             1;
58             __END__