OSDN Git Service

Plugin: add HttpCompression plugin
authorhylom <hylom@users.sourceforge.jp>
Mon, 1 Oct 2018 10:40:24 +0000 (19:40 +0900)
committerhylom <hylom@users.sourceforge.jp>
Mon, 1 Oct 2018 10:40:24 +0000 (19:40 +0900)
src/newslash_web/lib/Newslash/Plugin/HttpCompression.pm [new file with mode: 0644]
src/newslash_web/lib/Newslash/Web.pm

diff --git a/src/newslash_web/lib/Newslash/Plugin/HttpCompression.pm b/src/newslash_web/lib/Newslash/Plugin/HttpCompression.pm
new file mode 100644 (file)
index 0000000..d088911
--- /dev/null
@@ -0,0 +1,67 @@
+package Newslash::Plugin::HttpCompression;
+use Mojo::Base 'Mojolicious::Plugin';
+use IO::Compress::Gzip qw(gzip);
+use List::Util qw(any);
+use Data::Dumper;
+
+sub register {
+    my ($self, $app, $conf) = @_;
+
+    # set default config value
+    my $cnf = $app->config->{HttpCompression} ||= {};
+    $cnf->{enable} = 0 if !defined $cnf->{enable};
+
+    return if !$cnf->{enable};
+
+    $app->hook(after_render => sub {
+                   my ($c, $output, $format) = @_;
+
+                   # Check if user agent accepts gzip compression
+                   return unless ($c->req->headers->accept_encoding // '') =~ /gzip/i;
+
+                   # Check if content-type can be compressed
+                   if ( !any { $format eq $_ } (qw{html json})) {
+                       return;
+                   }
+
+                   # Add header
+                   $c->res->headers->append(Vary => 'Accept-Encoding');
+
+                   # Compress content with gzip
+                   $c->res->headers->content_encoding('gzip');
+                   gzip $output, \my $compressed;
+                   $$output = $compressed;
+               });
+}
+
+1;
+
+=encoding utf8
+
+=head1 NAME
+
+Newslash::Plugin::HttpCompression - gzip content-encoding support plugin
+
+=head1 SYNOPSIS
+
+  # Mojolicious
+  $app->plugin('Newslash::Plugin::HttpCompression');
+
+=head1 DESCRIPTION
+
+L<Newslash::Plugin::HttpCompression> porvides gzip content-encoding support
+to reduce network traffic.
+
+=head1 METHODS
+
+=head2 register
+
+  $plugin->register(Mojolicious->new);
+
+Register epoch in L<Mojolicious> application.
+
+=head1 SEE ALSO
+
+L<Mojolicious>, L<Mojolicious::Guides>, L<http://mojolicious.org>.
+
+=cut
index 0491f07..d699698 100644 (file)
@@ -211,6 +211,9 @@ sub startup {
     # AD renderer
     $app->plugin('Newslash::Plugin::ADRenderer');
 
+    # HTTP Compression
+    $app->plugin('Newslash::Plugin::HttpCompression');
+
 
     ############################################################
     #