Skip to content

Commit

Permalink
Implement :indexes option for static
Browse files Browse the repository at this point in the history
  • Loading branch information
Altai-man committed Mar 10, 2018
1 parent 49c656d commit 937d8f2
Show file tree
Hide file tree
Showing 3 changed files with 61 additions and 2 deletions.
16 changes: 14 additions & 2 deletions lib/Cro/HTTP/Router.pm6
Expand Up @@ -939,7 +939,7 @@ module Cro::HTTP::Router {
$resp.append-header('Cache-Control', $cache);
}

sub static(IO() $base, *@path, :$mime-types) is export {
sub static(IO() $base, *@path, :$mime-types, :@indexes) is export {
my $resp = $*CRO-ROUTER-RESPONSE //
die X::Cro::HTTP::Router::OnlyInHandler.new(:what<route>);
my $child = '.';
Expand All @@ -953,7 +953,19 @@ module Cro::HTTP::Router {

my sub get_or_404($path) {
if $path.e {
content $content-type, slurp($path, :bin);
if $path.d {
for @indexes {
my $index = $path.add($_);
if $index.e {
content $content-type, slurp($index, :bin);
return;
}
}
$resp.status = 404;
return;
} else {
content $content-type, slurp($path, :bin);
}
} else {
$resp.status = 404;
}
Expand Down
46 changes: 46 additions & 0 deletions t/http-router.t
Expand Up @@ -1845,4 +1845,50 @@ throws-like { response }, X::Cro::HTTP::Router::OnlyInHandler, what => 'response
}
}

{
my $app = route {
get -> {
static 't/samples/', :indexes(['index.xhtml']);
}

get -> 'index-plain' {
static 't/samples/', :indexes(['index.html', 'index.xhtml']);
}
get -> 'index-extended' {
static 't/samples/', :indexes(['index.xhtml', 'index.html']);
}
get -> 'no-index' {
static 't/samples/', :indexes([]);
}
}
my $source = Supplier.new;
my $responses = $app.transformer($source.Supply).Channel;
my $req = Cro::HTTP::Request.new(method => 'GET', target => '/');
$source.emit($req);
given $responses.receive -> $r {
is body-text($r), "<HTML>Extended</HTML>\n", 'Get value from index';
is $r.status, 200, 'Static sets correct status code';
}

$req = Cro::HTTP::Request.new(method => 'GET', target => '/index-plain');
$source.emit($req);
given $responses.receive -> $r {
is body-text($r), "<HTML></HTML>\n", 'static indexes order check, 1';
is $r.status, 200, 'Good status';
}

$req = Cro::HTTP::Request.new(method => 'GET', target => '/index-extended');
$source.emit($req);
given $responses.receive -> $r {
is body-text($r), "<HTML>Extended</HTML>\n", 'static indexes order check, 2';
is $r.status, 200, 'Good status';
}

$req = Cro::HTTP::Request.new(method => 'GET', target => '/no-index');
$source.emit($req);
given $responses.receive -> $r {
is $r.status, 404, 'No candidate served with empty indexes';
}
}

done-testing;
1 change: 1 addition & 0 deletions t/samples/index.xhtml
@@ -0,0 +1 @@
<HTML>Extended</HTML>

0 comments on commit 937d8f2

Please sign in to comment.