package Jaos::WebApp::Plugin::Static; use strict; use warnings; use base qw/Jaos::WebApp::Controller/; use Plack::MIME; sub register { my ($self, $app, $mapping) = @_; for my $url ( keys %$mapping ) { my $path = $mapping->{$url}; $url =~ s|/$||; $url = '/'.$url if ($url !~ m|^/|); if ($path !~ m/^\//) { $path = join('/',$app->appdir, $path); } $app->{__static_path}->{$url} = $path; $app->connect("$url/:file", controller => __PACKAGE__, action => 'serve'); $app->connect("$url/", controller => __PACKAGE__, action => 'list'); } } sub list { my ($self) = @_; (my $url = $self->app->req->path) =~ s|^(/[^/]+)/|$1|; my $path = $self->app->{__static_path}->{$url}; opendir(my $dir, $path) or do { $self->app->res->status('404'); return; }; my @files = grep { -f "$path/$_" } grep { ! m/^[\.]+$/ } sort readdir($dir); closedir($dir); my $listing = ''; $self->app->res->status(200); $self->app->res->header('Content-Type' => 'text/html'); $self->app->res->body($listing); } sub serve { my ($self) = @_; my $file = $self->param('file'); (my $url = $self->app->req->path) =~ s|^(/[^/]+)/.*|$1|; my $path = $self->app->{__static_path}->{$url}; my $filename = join('/', $path, $file); open my $fh, '<:raw', $filename or do { $self->app->res->status('404'); return; }; my @stat = stat $filename; my $mime = Plack::MIME->mime_type($file); $self->app->res->status(200); $self->app->res->header('Content-Type' => $mime || 'application/octect-stream'); $self->app->res->header('Content-Length' => $stat[7]); $self->app->res->body($fh); # this is closed for us #close($fh); } =head1 NAME Jaos::WebApp::Plugin::Static - Serve static files =head1 SYNOPSIS package MyApp; sub startup { my $app = shift; $app->load_plugin('Jaos::WebApp::Plugin::Static', { '/url' => 'local_path', '/url2' => '/abs_path' }); } 1; =head1 DESCRIPTION Jaos::WebApp::Plugin::Static is a simple plugin that serves static files and simple directory listings. =head1 METHODS =head2 register register connects routes for the given urls to paths. =head1 AUTHOR Jason Woodward =head1 LICENSE Copyright (C) 2010-2011 Jason Woodward All rights reserved This library is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this library. If not, see . =cut 1;