File Coverage

lib/PAGI/App/Redirect.pm
Criterion Covered Total %
statement 26 26 100.0
branch 5 6 83.3
condition 7 7 100.0
subroutine 7 7 100.0
pod 0 2 0.0
total 45 48 93.7


line stmt bran cond sub pod time code
1             package PAGI::App::Redirect;
2             $PAGI::App::Redirect::VERSION = '0.002000';
3 1     1   444 use strict;
  1         1  
  1         32  
4 1     1   4 use warnings;
  1         1  
  1         38  
5 1     1   4 use Future::AsyncAwait;
  1         1  
  1         5  
6 1     1   36 use PAGI::Response;
  1         1  
  1         431  
7              
8             =encoding UTF-8
9              
10             =head1 NAME
11              
12             PAGI::App::Redirect - URL redirect app for the dynamic case
13              
14             =head1 SYNOPSIS
15              
16             # The static case is just a response value (preferred):
17             use PAGI::Response;
18             $router->mount('/old' => PAGI::Response->redirect('/new', 301));
19              
20             # PAGI::App::Redirect is for the dynamic case — a coderef target
21             # and/or query-string preservation:
22             use PAGI::App::Redirect;
23             my $app = PAGI::App::Redirect->new(
24             to => sub { my ($scope) = @_; compute_target($scope) },
25             status => 302,
26             preserve_query => 1,
27             )->to_app;
28              
29             =cut
30              
31             sub new {
32 6     6 0 9237 my ($class, %args) = @_;
33              
34             return bless {
35             to => $args{to},
36             status => $args{status} // 302,
37 6   100     57 preserve_query => $args{preserve_query} // 1,
      100        
38             }, $class;
39             }
40              
41             sub to_app {
42 6     6 0 8 my ($self) = @_;
43              
44 6         10 my $to = $self->{to};
45 6         7 my $status = $self->{status};
46 6         7 my $preserve_query = $self->{preserve_query};
47              
48 6     6   66 return async sub {
49 6         10 my ($scope, $receive, $send) = @_;
50 6 100       14 my $location = ref $to eq 'CODE' ? $to->($scope) : $to;
51              
52 6 100 100     22 if ($preserve_query && $scope->{query_string}) {
53 1 50       6 my $sep = $location =~ /\?/ ? '&' : '?';
54 1         2 $location .= $sep . $scope->{query_string};
55             }
56              
57             await PAGI::Response->new($scope)
58             ->content_type('text/plain')
59             ->redirect($location, $status)
60 6         21 ->respond($send);
61 6         44 };
62             }
63              
64             1;
65              
66             __END__