File Coverage

blib/lib/Mojolicious/Plugin/RedirectHost.pm
Criterion Covered Total %
statement 27 27 100.0
branch 14 14 100.0
condition 3 5 60.0
subroutine 4 4 100.0
pod 1 1 100.0
total 49 51 96.0


line stmt bran cond sub pod time code
1             package Mojolicious::Plugin::RedirectHost;
2              
3 3     3   27467 use Mojo::Base 'Mojolicious::Plugin';
  3         6  
  3         23  
4 3     3   594 use Mojo::URL;
  3         7  
  3         26  
5              
6             our $VERSION = '1.05'; # VERSION
7              
8             # where to look for options
9             my $CONFIG_KEY = 'redirect_host';
10             my $DEFAULT_CODE = 301;
11             my $EXCEPT_PATH = '/robots.txt';
12              
13             sub register {
14 6     6 1 73732 my ($self, $app, $params) = @_;
15              
16 6         14 my %options;
17 6 100 50     66 if (ref $params eq 'HASH' && scalar keys %$params) {
    100          
18 4         17 %options = %$params;
19             }
20             elsif (ref $app->config($CONFIG_KEY) eq 'HASH') {
21 1         14 %options = %{$app->config($CONFIG_KEY)};
  1         5  
22             }
23              
24 6 100       60 unless ($options{host}) {
25 2         6 my $msg = 'RedirectHost plugin: define "host" option at least!';
26 2 100       33 $app->log->error($msg) unless $options{silent};
27              
28 2         43 return;
29             }
30              
31             $app->hook(
32             before_dispatch => sub {
33 9     9   205464 my $c = shift;
34 9         42 my $url = $c->req->url->to_abs;
35 9         5834 my $path = $c->req->url->path;
36              
37              
38             # don't need redirection
39 9 100       1181 return if $url->host eq $options{host};
40              
41             # except_robots?
42 8 100       118 if ($options{er}) {
43 6 100       30 return if $path eq $EXCEPT_PATH;
44             }
45              
46             # main host
47 6         374 $url->host($options{host});
48              
49             # code
50 6   66     56 $c->res->code($options{code} || $DEFAULT_CODE);
51              
52              
53 6         648 $c->redirect_to($url->to_string);
54             }
55 4         33 );
56              
57 4         144 return;
58             }
59              
60             1;
61              
62             # ABSTRACT: Redirects requests from mirrors to the main host (useful for SEO)
63              
64             __END__