example2.pl untested

filter: Statementstmt 0.0% 0 / 44 Branchbran 0.0% 0 / 6 Conditioncond 0.0% 0 / 15 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 6 Podpod n/a totaltotal 0.0% 0 / 71 CC 1 SCAR 6.9
CC
1
Cov
0%
BEGIN
2.0
BEGIN
2.0
BEGIN
2.0
CRAP 2.0
1 #!/usr/bin/env perl
2  
3 # more complex example returning JSON or static content
4  
5 use 5.10.0;
6 use strict;
7 use warnings;
8  
9 use Limper;
10 use File::Slurp;
11 use JSON;
12  
13 my $document_root = './public/';
14  
15 my $static = sub {
16 my $file = request->{uri};
17 $file =~ s{^/}{$document_root};
18 if ($file =~ qr{/\.\./}) {
19 status 403;
20 return 'lolnope';
21 }
22 if (-e $file and -r $file and -f $file) {
23 $file =~ /\.html$/ and headers 'Content-Type' => 'text/html';
24 scalar read_file $file;
25 } elsif (-e $file and -r $file and -d $file) {
26 opendir my($dh), $file;
27 my @files = sort grep { !/^\./ } readdir $dh;
28 @files = map { "<a href=\"$_\">$_</a><br>" } @files;
29 headers 'Content-Type' => 'text/html';
30 join "\n", '<html><head><title>Directory listing of ' . request->{uri} . '</title></head><body>', @files, '</body></html>';
31 } else {
32 status 404;
33 'blegh';
34 }
35 };
36  
37 my $generic = sub {
38 headers('Content-Type' => 'application/json');
39 JSON->new->encode({status => 'OK'});
40 };
41  
42 get qr{^/} => $static;
43 post qr{^/} => $generic;
44  
45 limp(LocalAddr => '0.0.0.0');