File Coverage

lib/PAGI/App/Redirect.pm
Criterion Covered Total %
statement 22 24 91.6
branch 3 6 50.0
condition 4 7 57.1
subroutine 6 6 100.0
pod 0 2 0.0
total 35 45 77.7


line stmt bran cond sub pod time code
1             package PAGI::App::Redirect;
2              
3 1     1   391 use strict;
  1         1  
  1         28  
4 1     1   3 use warnings;
  1         1  
  1         35  
5 1     1   3 use Future::AsyncAwait;
  1         1  
  1         5  
6              
7             =head1 NAME
8              
9             PAGI::App::Redirect - URL redirect app
10              
11             =head1 SYNOPSIS
12              
13             use PAGI::App::Redirect;
14              
15             my $app = PAGI::App::Redirect->new(
16             to => '/new-location',
17             status => 301,
18             )->to_app;
19              
20             =cut
21              
22             sub new {
23 3     3 0 5492 my ($class, %args) = @_;
24              
25             return bless {
26             to => $args{to},
27             status => $args{status} // 302,
28 3   100     27 preserve_query => $args{preserve_query} // 1,
      50        
29             }, $class;
30             }
31              
32             sub to_app {
33 3     3 0 6 my ($self) = @_;
34              
35 3         7 my $to = $self->{to};
36 3         5 my $status = $self->{status};
37 3         4 my $preserve_query = $self->{preserve_query};
38              
39 3     3   85 return async sub {
40 3         6 my ($scope, $receive, $send) = @_;
41 3 100       11 my $location = ref $to eq 'CODE' ? $to->($scope) : $to;
42              
43 3 50 33     16 if ($preserve_query && $scope->{query_string}) {
44 0 0       0 my $sep = $location =~ /\?/ ? '&' : '?';
45 0         0 $location .= $sep . $scope->{query_string};
46             }
47              
48             await $send->({
49             type => 'http.response.start',
50             status => $status,
51             headers => [
52             ['location', $location],
53             ['content-type', 'text/plain'],
54             ['content-length', 0],
55             ],
56 3         15 });
57 3         164 await $send->({ type => 'http.response.body', body => '', more => 0 });
58 3         15 };
59             }
60              
61             1;
62              
63             __END__