Skip to content

Commit

Permalink
Implement a static middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
lestrrat committed Oct 20, 2015
1 parent 8df6695 commit e1c5a6c
Show file tree
Hide file tree
Showing 5 changed files with 88 additions and 0 deletions.
54 changes: 54 additions & 0 deletions lib/Crust/Middleware/Static.pm6
@@ -0,0 +1,54 @@
use v6;
use Crust::App::File;
use Crust::Middleware;

unit class Crust::Middleware::Static is Crust::Middleware;

has $.file;
has $.path;
has $.root;
has $.encoding;
has $.pass-through;
has $.content-type;

submethod BUILD(:$!path, :$!root, :$!encoding, :$!content-type, :$!pass-through) {
$!path //= sub ($env, %path) { True };
$!root //= ".";
$!encoding //= "iso-8859-1";
$!content-type //= "";
$!file = Crust::App::File.new(
:root($!root),
:encoding($!encoding),
:content-type($!content-type),
);
}

method CALL-ME(%env) {
my @res = self!handle-static(%env);
if @res && ! ($.pass-through && @res[0] == 404) {
return @res;
}

return $.app.(%env);
}

method !handle-static(%env) {
my $path_match = $.path;
if ! $path_match {
return;
}

my $path = %env<PATH_INFO>;
my $proceed;

given $path_match {
when Callable { ($proceed, $path) = $path_match($path, %env) }
when Regex { $proceed = $path ~~ $path }
}
if !$proceed {
return;
}

temp %env<PATH_INFO> = $path;
return $!file.call(%env);
}
Empty file added share/#foo
Empty file.
Binary file added share/baybridge.jpg
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added share/face.jpg
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
34 changes: 34 additions & 0 deletions t/Crust-Middleware/static.t
@@ -0,0 +1,34 @@
use v6;
use Test;
use Crust::Test;
use Crust::Builder;
use Crust::Middleware::Static;
use HTTP::Request;

$Crust::Test::Impl = "MockHTTP";

# TODO: Need to port more tests

my $app = builder {
enable "Static",
path => sub {
# Perl6 strings are immutable, so you can't just modify
# the path and expect the changes to be visible from the caller
my $match = @_[0].subst-mutate(rx<^ '/share/'>, "");
return ($match, @_[0]);
},
root => "share";
-> %env {
200, [ 'Content-Type' => 'text/plain' ], [ 'Hello World' ];
};
};

test-psgi
client => -> $cb {
my $req = HTTP::Request.new(GET => "http://localhost/share/face.jpg");
my $res = $cb($req);
is $res.code, 200;
},
app => $app;

done-testing;

0 comments on commit e1c5a6c

Please sign in to comment.