Skip to content

Commit

Permalink
improved Mojolicious::Static to allow custom content types
Browse files Browse the repository at this point in the history
  • Loading branch information
kraih committed Aug 18, 2014
1 parent 190e919 commit 65236ec
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 3 deletions.
1 change: 1 addition & 0 deletions Changes
@@ -1,5 +1,6 @@

5.31 2014-08-18
- Improved Mojolicious::Static to allow custom content types.

5.30 2014-08-17
- Improved Mojolicious::Static to only handle GET and HEAD requests.
Expand Down
11 changes: 8 additions & 3 deletions lib/Mojolicious/Static.pm
Expand Up @@ -80,10 +80,15 @@ sub is_fresh {

sub serve {
my ($self, $c, $rel) = @_;

return undef unless my $asset = $self->file($rel);
my $types = $c->app->types;
my $type = $rel =~ /\.(\w+)$/ ? $types->type($1) : undef;
$c->res->headers->content_type($type || $types->type('txt'));

my $types = $c->app->types;
my $type = $rel =~ /\.(\w+)$/ ? $types->type($1) : undef;
my $headers = $c->res->headers;
$headers->content_type($type || $types->type('txt'))
unless $headers->content_type;

return !!$self->serve_asset($c, $asset);
}

Expand Down
15 changes: 15 additions & 0 deletions t/mojolicious/static_lite_app.t
Expand Up @@ -12,6 +12,12 @@ use Test::Mojo;

get '/hello3.txt' => sub { shift->render_static('hello2.txt') };

post '/hello4.txt' => sub {
my $c = shift;
$c->res->headers->content_type('text/html');
$c->render_static('hello2.txt');
};

options '/hello.txt' => sub { shift->render(text => 'Options!') };

get '/etag' => sub {
Expand Down Expand Up @@ -63,6 +69,10 @@ $t->options_ok('/hello.txt')->status_is(200)
->header_is(Server => 'Mojolicious (Perl)')
->header_is('Content-Length' => 8)->content_is('Options!');

# Unknown method
$t->put_ok('/hello.txt')->status_is(404)
->header_is(Server => 'Mojolicious (Perl)');

# Partial static file
$t->get_ok('/hello.txt' => {Range => 'bytes=2-8'})->status_is(206)
->header_is(Server => 'Mojolicious (Perl)')
Expand Down Expand Up @@ -123,6 +133,11 @@ $t->get_ok('/hello3.txt' => {Range => 'bytes=0-0'})->status_is(206)
->header_is('Accept-Ranges' => 'bytes')->header_is('Content-Length' => 1)
->header_is('Content-Range' => 'bytes 0-0/1')->content_is('X');

# Render static file with custom content type
$t->post_ok('/hello4.txt')->status_is(200)
->header_is(Server => 'Mojolicious (Perl)')->content_type_is('text/html')
->header_is('Content-Length' => 1)->content_is('X');

# Fresh content
$t->get_ok('/etag')->status_is(200)->header_is(Server => 'Mojolicious (Perl)')
->header_is(ETag => '"abc"')->content_is('I ♥ Mojolicious!');
Expand Down

0 comments on commit 65236ec

Please sign in to comment.