1 package Catalyst::Plugin::Static::Simple;
4 use base qw/Class::Accessor::Fast Class::Data::Inheritable/;
10 our $VERSION = '0.08';
12 __PACKAGE__->mk_classdata( qw/_static_mime_types/ );
13 __PACKAGE__->mk_accessors( qw/_static_file
15 _static_debug_message/ );
17 # prepare_action is used to first check if the request path is a static file.
18 # If so, we skip all other prepare_action steps to improve performance.
21 my $path = $c->req->path;
23 # is the URI in a static-defined path?
24 foreach my $dir ( @{ $c->config->{static}->{dirs} } ) {
25 my $re = ( $dir =~ /^qr\//xms ) ? eval $dir : qr/^${dir}/;
27 $c->error( "Error compiling static dir regex '$dir': $@" );
30 if ( $c->_locate_static_file ) {
31 $c->_debug_msg( "from static directory" )
32 if ( $c->config->{static}->{debug} );
35 $c->_debug_msg( "404: file not found: $path" )
36 if ( $c->config->{static}->{debug} );
37 $c->res->status( 404 );
43 # Does the path have an extension?
44 if ( $path =~ /.*\.(\S{1,})$/xms ) {
46 return if ( $c->_locate_static_file );
49 return $c->NEXT::prepare_action(@_);
52 # dispatch takes the file found during prepare_action and serves it
56 return if ( $c->res->status != 200 );
58 if ( $c->_static_file ) {
59 if ( $c->config->{static}->{no_logs} ) {
60 if ( $c->log->can('abort') ) { $c->log->abort(1) ; }
62 return $c->_serve_static;
65 return $c->NEXT::dispatch(@_);
69 # finalize serves up final header information
73 # display all log messages
74 if ( $c->config->{static}->{debug} && scalar @{$c->_debug_msg} ) {
75 $c->log->debug( "Static::Simple: Serving " .
76 join( " ", @{$c->_debug_msg} ) );
79 # return DECLINED when under mod_perl
80 if ( $c->config->{static}->{use_apache} && $c->_static_apache_mode ) {
81 my $engine = $c->_static_apache_mode;
83 if ( $engine == 13 ) {
84 return Apache::Constants::DECLINED;
86 elsif ( $engine == 19 ) {
87 return Apache::Const::DECLINED;
89 elsif ( $engine == 20 ) {
90 return Apache2::Const::DECLINED;
94 if ( $c->res->status =~ /^(1\d\d|[23]04)$/xms ) {
95 $c->res->headers->remove_content_headers;
96 return $c->finalize_headers;
99 return $c->NEXT::finalize(@_);
107 $c->config->{static}->{dirs} ||= [];
108 $c->config->{static}->{include_path} ||= [ $c->config->{root} ];
109 $c->config->{static}->{mime_types} ||= {};
110 $c->config->{static}->{use_apache} ||= 0;
111 $c->config->{static}->{debug} ||= $c->debug;
112 $c->config->{static}->{no_logs} ||= 1;
114 # load up a MIME::Types object, only loading types with
115 # at least 1 file extension
116 $c->_static_mime_types( MIME::Types->new( only_complete => 1 ) );
118 # preload the type index hash so it's not built on the first request
119 $c->_static_mime_types->create_type_index;
122 # Search through all included directories for the static file
123 # Based on Template Toolkit INCLUDE_PATH code
124 sub _locate_static_file {
127 my $path = $c->req->path;
129 my @ipaths = @{ $c->config->{static}->{include_path} };
131 my $count = 64; # maximum number of directories to search
133 while ( @ipaths && --$count) {
134 my $dir = shift @ipaths || next;
136 if ( ref $dir eq 'CODE' ) {
137 eval { $dpaths = &$dir( $c ) };
139 $c->log->error( "Static::Simple: include_path error: " . $@ );
141 unshift( @ipaths, @$dpaths );
146 if ( -d $dir && -f $dir . '/' . $path ) {
147 $c->_debug_msg( $dir . "/" . $path )
148 if ( $c->config->{static}->{debug} );
149 return $c->_static_file( $dir . '/' . $path );
160 my $path = $c->req->path;
162 # abort if running under mod_perl
163 # note that we do not use the Apache method if the user has defined
164 # custom MIME types or is using include paths, as Apache would not know
168 if ( $c->config->{static}->{use_apache} ) {
169 # check engine version
170 last APACHE_CHECK unless $c->engine =~ /Apache::MP(\d{2})/xms;
173 # skip if we have user-defined MIME types
174 last APACHE_CHECK if keys %{ $c->config->{static}->{mime_types} };
176 # skip if the file is in a user-defined include path
177 last APACHE_CHECK if $c->_static_file
178 ne $c->config->{root} . '/' . $path;
180 # check that Apache will serve the correct file
181 if ( $c->apache->document_root ne $c->config->{root} ) {
182 $c->log->warn( "Static::Simple: Your Apache DocumentRoot"
183 . " must be set to " . $c->config->{root}
184 . " to use the Apache feature. Yours is"
185 . " currently " . $c->apache->document_root
189 $c->_debug_msg( "DECLINED to Apache" )
190 if ( $c->config->{static}->{debug} );
191 $c->_static_apache_mode( $engine );
197 my $type = $c->_ext_to_type;
199 my $full_path = $c->_static_file;
200 my $stat = stat( $full_path );
202 # the below code all from C::P::Static
203 if ( $c->req->headers->if_modified_since ) {
204 if ( $c->req->headers->if_modified_since == $stat->mtime ) {
205 $c->res->status( 304 ); # Not Modified
206 $c->res->headers->remove_content_headers;
211 my $content = read_file( $full_path );
212 $c->res->headers->content_type( $type );
213 $c->res->headers->content_length( $stat->size );
214 $c->res->headers->last_modified( $stat->mtime );
215 $c->res->output( $content );
219 # looks up the correct MIME type for the current file extension
222 my $path = $c->req->path;
224 if ( $path =~ /.*\.(\S{1,})$/xms ) {
226 my $user_types = $c->config->{static}->{mime_types};
227 my $type = $user_types->{$ext}
228 || $c->_static_mime_types->mimeTypeOf( $ext );
230 $c->_debug_msg( "as $type" )
231 if ( $c->config->{static}->{debug} );
235 $c->_debug_msg( "as text/plain (unknown extension $ext)" )
236 if ( $c->config->{static}->{debug} );
241 $c->_debug_msg( 'as text/plain (no extension)' )
242 if ( $c->config->{static}->{debug} );
248 my ( $c, $msg ) = @_;
250 if ( !defined $c->_static_debug_message ) {
251 $c->_static_debug_message( [] );
255 push @{ $c->_static_debug_message }, $msg;
258 return $c->_static_debug_message;
266 Catalyst::Plugin::Static::Simple - Make serving static pages painless.
271 MyApp->setup( qw/Static::Simple/ );
275 The Static::Simple plugin is designed to make serving static content in your
276 application during development quick and easy, without requiring a single
277 line of code from you.
279 It will detect static files used in your application by looking for file
280 extensions in the URI. By default, you can simply load this plugin and it
281 will immediately begin serving your static files with the correct MIME type.
282 The light-weight MIME::Types module is used to map file extensions to
283 IANA-registered MIME types.
285 Note that actions mapped to paths using periods (.) will still operate
288 You may further tweak the operation by adding configuration options, described
291 =head1 ADVANCED CONFIGURATION
293 Configuration is completely optional and is specified within
294 MyApp->config->{static}. If you use any of these options, the module will
295 probably feel less "simple" to you!
297 =head2 Aborting request logging
299 With Catalyst 5.50, there has been added support for dropping logging for a
300 request. We've turned this on by default, as static logging tends to clutter
301 the Log API, however, if you want logging of static requests, you can easily
302 turn it on by setting MyApp->config->{static}->{no_logs} to 0.
304 =head2 Forcing directories into static mode
306 Define a list of top-level directories beneath your 'root' directory that
307 should always be served in static mode. Regular expressions may be
308 specified using qr//.
310 MyApp->config->{static}->{dirs} = [
315 =head2 Including additional directories (experimental!)
317 You may specify a list of directories in which to search for your static
318 files. The directories will be searched in order and will return the first
319 file found. Note that your root directory is B<not> automatically added to
320 the search path when you specify an include_path. You should use
321 MyApp->config->{root} to add it.
323 MyApp->config->{static}->{include_path} = [
326 MyApp->config->{root}
329 With the above setting, a request for the file /images/logo.jpg will search
330 for the following files, returning the first one found:
332 /path/to/overlay/images/logo.jpg
333 /dynamic/path/images/logo.jpg
334 /your/app/home/root/images/logo.jpg
336 The include path can contain a subroutine reference to dynamically return a
337 list of available directories. This method will receive the $c object as a
338 parameter and should return a reference to a list of directories. Errors can
339 be reported using die(). This method will be called every time a file is
340 requested that appears to be a static file (i.e. it has an extension).
344 sub incpath_generator {
347 if ( $c->session->{customer_dir} ) {
348 return [ $c->session->{customer_dir} ];
350 die "No customer dir defined.";
354 =head2 Custom MIME types
356 To override or add to the default MIME types set by the MIME::Types module,
357 you may enter your own extension to MIME type mapping.
359 MyApp->config->{static}->{mime_types} = {
364 =head2 Apache integration and performance
366 Optionally, when running under mod_perl, Static::Simple can return DECLINED
367 on static files to allow Apache to serve the file. A check is first done to
368 make sure that Apache's DocumentRoot matches your Catalyst root, and that you
369 are not using any custom MIME types or multiple roots. To enable the Apache
370 support, you can set the following option.
372 MyApp->config->{static}->{use_apache} = 1;
374 By default this option is disabled because after several benchmarks it
375 appears that just serving the file from Catalyst is the better option. On a
376 3K file, Catalyst appears to be around 25% faster, and is 42% faster on a 10K
377 file. My benchmarking was done using the following 'siege' command, so other
378 benchmarks would be welcome!
380 siege -u http://server/static/css/10K.css -b -t 1M -c 1
382 For best static performance, you should still serve your static files directly
383 from Apache by defining a Location block similar to the following:
386 SetHandler default-handler
389 =head2 Bypassing other plugins
391 This plugin checks for a static file in the prepare_action stage. If the
392 request is for a static file, it will bypass all remaining prepare_action
393 steps. This means that by placing Static::Simple before all other plugins,
394 they will not execute when a static file is found. This can be helpful by
395 skipping session cookie checks for example. Or, if you want some plugins
396 to run even on static files, list them before Static::Simple.
398 Currently, work done by plugins in any other prepare method will execute
401 =head2 Debugging information
403 Enable additional debugging information printed in the Catalyst log. This
404 is automatically enabled when running Catalyst in -Debug mode.
406 MyApp->config->{static}->{debug} = 1;
410 L<Catalyst>, L<Catalyst::Plugin::Static>,
411 L<http://www.iana.org/assignments/media-types/>
415 Andy Grundman, <andy@hybridized.org>
419 The authors of Catalyst::Plugin::Static:
425 For the include_path code from Template Toolkit:
431 This program is free software, you can redistribute it and/or modify it under
432 the same terms as Perl itself.