Skip to content

Instantly share code, notes, and snippets.

@hdp
Created March 18, 2011 19:26
Show Gist options
  • Save hdp/876679 to your computer and use it in GitHub Desktop.
Save hdp/876679 to your computer and use it in GitHub Desktop.
use strict;
use warnings;
use Plack::Builder;
use Plack::App::File;
sub slashify_if (&) {
my $code = shift;
return sub {
my $app = shift;
return sub {
my $env = shift;
if ($code->($env)) {
my $host = $env->{HTTP_HOST}
|| "$env->{SERVER_NAME}:$env->{SERVER_PORT}";
my $qs = length $env->{QUERY_STRING}
? "?$env->{QUERY_STRING}"
: "";
return [ 302, [
Location =>
"$env->{'psgi.url_scheme'}://$host$env->{SCRIPT_NAME}$env->{PATH_INFO}/$qs"
], [] ];
} else {
return $app->($env);
}
}
}
}
builder {
my $root = '.';
my @indexes = qw(index.html index.htm);
enable slashify_if {
$_[0]->{PATH_INFO} !~ m{/\.\.(/|$)} and
$_[0]->{PATH_INFO} =~ m{(^|[^/])$} and
-d "$root/$_[0]->{PATH_INFO}"
};
enable_if { $_[0]->{PATH_INFO} =~ m{/$} } sub {
my $app = shift;
sub {
my $env = shift;
for my $i (@indexes) {
if (-e "$root/$env->{PATH_INFO}$i") {
$env->{PATH_INFO} .= $i;
last;
}
}
return $app->($env);
}
};
Plack::App::File->new(root => $root)->to_app;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment