Redirect



examples/dancer/redirection/app.psgi
package App;
use Dancer2;

get '/' => sub {
    return q{
        <html><head><title>Redirection</title></head><body>
        <h1>Main Page</h1>
        <a href="/go/home">Go home</a><br>
        <a href="/go/away">Go away</a><br>
        <a href="/go/elsewhere">Go elsewhere</a><br>
        </body></html>
    };
};

get '/home' => sub {
    return '<h1>Home</h1>Back to the <a href="/">main page</a>';
};


get '/go/:to' => sub {
    my $to = route_parameters->get('to');
    if ($to eq 'home') {
        redirect '/home';
    }
    if ($to eq 'away') {
        redirect 'https://perlmaven.com/';
    }
    return 'Invalid redirect';
};

App->to_app;

examples/dancer/redirection/test.t
use strict;
use warnings;

use Test::More;
use Plack::Test;
use Plack::Util;
use HTTP::Request::Common;

my $app = Plack::Util::load_psgi './app.psgi';

my $test = Plack::Test->create($app);

subtest redirect => sub {
   my $res = $test->request(GET '/go/home');
   is $res->status_line, '302 Found', 'Status';
   is $res->headers->{location}, '/home';
};

subtest redirect_away => sub {
   my $res = $test->request(GET '/go/away');
   is $res->status_line, '302 Found', 'Status';
   is $res->headers->{location}, 'https://perlmaven.com/';
};

subtest redirect_other => sub {
   my $res = $test->request(GET '/go/other');
   is $res->status_line, '200 OK', 'Status';
   ok not exists $res->headers->{location};
   is $res->content, 'Invalid redirect';
};


done_testing();