JSORB::Server::Traits::WithStaticFiles - A JSORB::Server::Simple trait for static files


JSORB documentation Contained in the JSORB distribution.

Index


Code Index:

NAME

Top

JSORB::Server::Traits::WithStaticFiles - A JSORB::Server::Simple trait for static files

SYNOPSIS

Top

  JSORB::Server::Simple->new_with_traits(
      traits     => [ 'JSORB::Server::Traits::WithStaticFiles' ],
      doc_root   => [ $FindBin::Bin, '..', '..' ],
      dispatcher => JSORB::Dispatcher::Path->new(
          namespace => $ns,
      )
  )->run;

DESCRIPTION

Top

This is basically just a simple way to serve static files through your simple JSORB server. Its detection of files is very niave, you have been warned (patches welcome).

BUGS

Top

All complex software has bugs lurking in it, and this module is no exception. If you find a bug please either email me, or add the bug to cpan-RT.

AUTHOR

Top

Stevan Little <stevan.little@iinteractive.com>

COPYRIGHT AND LICENSE

Top


JSORB documentation Contained in the JSORB distribution.

package JSORB::Server::Traits::WithStaticFiles;
use Moose::Role;
use MooseX::Types::Path::Class;

our $VERSION   = '0.04';
our $AUTHORITY = 'cpan:STEVAN';

has 'doc_root' => (
    is       => 'ro',
    isa      => 'Path::Class::Dir',
    coerce   => 1,
    required => 1,
);

around 'build_handler' => sub {
    my $next    = shift;
    my $self    = shift;
    my $handler = $self->$next(@_);

    return sub {
        my $request = shift;

        # NOTE:
        # this is **extremely** niave, it simply
        # tests for something that looks like a
        # file by seeing if the path has a trailing
        # extension, but even that is done poorly
        # so at some point this will need to be
        # fixed to be more sane in some way.
        # - SL
        if ($request->uri =~ /\/(.*\.[a-zA-Z]+)$/) {

            my $file = $self->doc_root->file($1);

            return HTTP::Response->new( 404, 'File Not Found' )
                unless -e $file;

            my $contents = $file->slurp;

            return HTTP::Response->new(
                200,
                'OK',
                [ "Content-length" => length $contents ],
                $contents
            );
        }

        $handler->($request);
    }
};

no Moose::Role; 1;

__END__