NAME
HTTP::CDN - Serve static files with unique URLs and far-future expiry
SYNOPSIS
To use this module in your Catalyst app, see Catalyst::Plugin::CDN. For other uses, see below:
my
$cdn
= HTTP::CDN->new(
root
=>
'/path/to/static/root'
,
base
=>
'/cdn/'
,
plugins
=> [
qw(
CSS::LESSp
CSS
CSS::Minifier::XS
JavaScript::Minifier::XS
)
],
);
# Generate a URL based on hashed file contents
say
$cdn
->resolve(
'css/style.less'
);
# e.g.: "/cdn/css/style.B97EA317759D.less"
# Find source file, apply plugins and return content
my
(
$uri
,
$hash
) =
$cdn
->unhash_uri(
'css/style.B97EA317759D.less'
);
return
$cdn
->filedata(
$uri
);
In a real application you'd also want to add a Content-Type header using the MIME type set by the plugins as well as headers for cache-control and expiry. You can trivially mount a handler to do all of that for the static content in your Plack app (using the HTTP::CDN object as defined above):
use
Plack::Builder;
my
$app
=
sub
{
# Define Plack app here
};
builder {
mount
'/cdn/'
=>
$cdn
->to_plack_app;
mount
'/'
=>
$app
;
}
DESCRIPTION
Web application plugin for serving static files with content-hashed unique URLs and far-future expiry.
Additionally provides automatic minification/compiling of css/less/javascript.
METHODS
new
Construct an object for generating URL paths and also for producing the response content for a requested URL. The constructor accepts these names options:
- root
-
Filesystem path to the directory where your static files are stored.
This option is required and has no default value.
- base
-
URL path prefix to be added when generating unique URL paths. Defaults to no prefix. A typical value might be '/cdn/'.
- plugins
-
A list of plugins that you wish to enable. Default value is:
[ 'HTTP::CDN::CSS' ]
.
resolve
Takes a URL path of a file in the root
directory and returns a CDN URL with base
prefix and content hash added.
unhash_uri
Takes a URI path and returns the same path with content hash removed. In list context, the hash is also returned.
Note: This method does not attempt to strip the base
prefix (e.g.: /cdn/
) from the URI path as that would usually have been done already by the application framework's routing layer.
fileinfo
Takes a URI path (with hash removed) and returns a hash of information about the file and its contents.
filedata
Takes a URI path (with hash removed) and returns the contents of that file with any plug-in transformations applied.
to_plack_app
Returns a subroutine reference that can be used as a Plack application - typically 'mounted' on a URL path like /cdn/
as shown in the SYNOPSIS.
AUTHOR
Martyn Smith <martyn@dollyfish.net.nz>
COPYRIGHT AND LICENSE
Copyright (C) 2010-2012 by Martyn Smith
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.