| 1 | package PAGI::App::Redirect; | ||
| 2 | $PAGI::App::Redirect::VERSION = '0.002001'; | ||
| 3 | use strict; | ||
| 4 | use warnings; | ||
| 5 | use Future::AsyncAwait; | ||
| 6 | use PAGI::Response; | ||
| 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 | my ($class, %args) = @_; | ||
| 33 | |||
| 34 | return bless { | ||
| 35 | to => $args{to}, | ||
| 36 | status => $args{status} // 302, | ||
| 37 | preserve_query => $args{preserve_query} // 1, | ||
| 38 | }, $class; | ||
| 39 | } | ||
| 40 | |||
| 41 | sub to_app { | ||
| 42 | my ($self) = @_; | ||
| 43 | |||
| 44 | my $to = $self->{to}; | ||
| 45 | my $status = $self->{status}; | ||
| 46 | my $preserve_query = $self->{preserve_query}; | ||
| 47 | |||
| 48 | return async sub { | ||
| 49 | my ($scope, $receive, $send) = @_; | ||
| 50 | my $location = ref $to eq 'CODE' ? $to->($scope) : $to; | ||
| 51 | |||
| 52 | if ($preserve_query && $scope->{query_string}) { | ||
| 53 | my $sep = $location =~ /\?/ ? '&' : '?'; | ||
| 54 | $location .= $sep . $scope->{query_string}; | ||
| 55 | } | ||
| 56 | |||
| 57 | await PAGI::Response->new($scope) | ||
| 58 | ->content_type('text/plain') | ||
| 59 | ->redirect($location, $status) | ||
| 60 | ->respond($send); | ||
| 61 | }; | ||
| 62 | } | ||
| 63 | |||
| 64 | 1; | ||
| 65 | |||
| 66 | __END__ |