OSDN Git Service

Plugin: add Redirect plugin
authorhylom <hylom@users.osdn.me>
Wed, 5 Jun 2019 11:54:28 +0000 (11:54 +0000)
committerhylom <hylom@users.osdn.me>
Wed, 5 Jun 2019 11:54:28 +0000 (11:54 +0000)
src/newslash_web/lib/Newslash/Plugin/Redirect.pm [new file with mode: 0644]
src/newslash_web/lib/Newslash/Web.pm

diff --git a/src/newslash_web/lib/Newslash/Plugin/Redirect.pm b/src/newslash_web/lib/Newslash/Plugin/Redirect.pm
new file mode 100644 (file)
index 0000000..ce99a9d
--- /dev/null
@@ -0,0 +1,61 @@
+package Newslash::Plugin::Redirect;
+use Mojo::Base 'Mojolicious::Plugin';
+use Mojo::Util qw(md5_sum dumper);
+use List::Util qw(any);
+use Socket;
+
+=encoding utf8
+
+=head1 NAME
+
+Newslash::Plugin::Redirect - redirect control plugin for Newslash
+
+=head1 SYNOPSIS
+
+  # Mojolicious
+  $app->plugin('Newslash::Plugin::Redirect');
+
+=head1 DESCRIPTION
+
+L<Newslash::Plugin::Redirect> controls redirection.
+
+
+=head1 METHODS
+
+=head2 register
+
+  $plugin->register(Mojolicious->new);
+
+Register hooks in L<Mojolicious> application.
+
+=cut
+
+sub register {
+    my ($self, $app, $conf) = @_;
+
+    $app->hook(around_dispatch => sub {
+                my ($next, $c) = @_;
+
+                # check subdomain redirection
+                my $hostname = ($c->config->{Site} || {})->{hostname} || "";
+                if ($hostname) {
+                  my $request_host = $c->req->url->to_abs->host_port;
+                  if ($request_host ne $hostname) {
+                    my $subdomain = $request_host;
+                    $subdomain =~ s/\.$hostname$//;
+
+                    if ($subdomain) {
+                      my $new_url = $c->req->url;
+                      $new_url->host($hostname);
+                      $c->res->code(301);
+                      $c->redirect_to($new_url);
+                      return;
+                    }
+                  }
+                }
+                $next->();
+              });
+}
+
+
+1;
index 71242dc..c5ad0a2 100644 (file)
@@ -128,6 +128,9 @@ sub startup {
     # enable access logging
     $app->plugin('Newslash::Plugin::AccessLog');
 
+    # redirect handlers
+    $app->plugin('Newslash::Plugin::Redirect');
+
     # Helpers for Newslash
     $app->plugin('Newslash::Plugin::NewslashHelpers');