Skip to content

Instantly share code, notes, and snippets.

@daxim
Created November 7, 2021 20:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save daxim/99376cdbd7a87b18986f7c1cec827abd to your computer and use it in GitHub Desktop.
Save daxim/99376cdbd7a87b18986f7c1cec827abd to your computer and use it in GitHub Desktop.
#!/usr/bin/env plackup
use HTTP::Status qw(HTTP_OK HTTP_BAD_REQUEST);
use Plack::App::File qw();
use Plack::Request qw();
use Path::Tiny qw(path);
use Text::Xslate qw();
my $docroot = path '/usr/share/doc/perl';
my $template = <<'...';
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>kapitaali_com download demo</title>
</head>
<body>
<form method="post">
<datalist id="available">
: for $files -> $f {
<option value="<: $f :>" />
: }
</datalist>
<label for="filename">Pick a file name:</label>
<input id="filename" list="available" name="filename" type="text" />
<input type="submit" />
</form>
</body>
</html>
...
my $app = sub {
my ($env) = @_;
my $req = Plack::Request->new($env);
if ('POST' eq $req->method) {
my $rel = $req->body_parameters->get('filename');
die unless $rel;
my $abs = path($rel)->absolute($docroot)->realpath;
# must be under docroot
return $req->new_response(
HTTP_BAD_REQUEST,
['Content-Type' => 'text/plain'],
['bad file name']
)->finalize unless $docroot->subsumes($abs);
my $res = $req->new_response(
Plack::App::File->serve_path($env, $abs->stringify)->@*
);
# force download
$res->content_type('application/octet-stream');
return $res->finalize;
}
return $req->new_response(
HTTP_OK,
['Content-Type' => 'application/xhtml+xml'],
[Text::Xslate->new->render_string($template, {files => [
map {$_->relative($docroot)->stringify}
grep {-f -r $_}
$docroot->children
]})]
)->finalize;
};
requires 'HTTP::Status';
requires 'Plack::App::File';
requires 'Plack::Request';
requires 'Path::Tiny';
requires 'Starlight';
requires 'Text::Xslate';
FROM perl:5.34
RUN mkdir -p /srv/kapitaali_com-download-demo
COPY . /srv/kapitaali_com-download-demo
WORKDIR /srv/kapitaali_com-download-demo
RUN cpanm --installdeps -n .
CMD [ "starlight" ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment