File: ConditionalGET.pm

package info (click to toggle)
libplack-perl 0.9941-1
  • links: PTS, VCS
  • area: main
  • in suites: squeeze
  • size: 1,444 kB
  • ctags: 592
  • sloc: perl: 7,155; makefile: 2
file content (71 lines) | stat: -rw-r--r-- 1,707 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package Plack::Middleware::ConditionalGET;
use strict;
use parent qw( Plack::Middleware );
use Plack::Util;

sub call {
    my $self = shift;
    my $env  = shift;

    my $res = $self->app->($env);
    return $res unless $env->{REQUEST_METHOD} =~ /^(GET|HEAD)$/;

    $self->response_cb($res, sub {
        my $res = shift;
        my $h = Plack::Util::headers($res->[1]);
        if ( $self->etag_matches($h, $env) || $self->not_modified_since($h, $env) ) {
            $res->[0] = 304;
            $h->remove($_) for qw( Content-Type Content-Length Content-Disposition );
            $res->[2] = [];
        }
    });
}

no warnings 'uninitialized';

sub etag_matches {
    my($self, $h, $env) = @_;
    $h->exists('ETag') && $h->get('ETag') eq _value($env->{HTTP_IF_NONE_MATCH});
}

sub not_modified_since {
    my($self, $h, $env) = @_;
    $h->exists('Last-Modified') && $h->get('Last-Modified') eq _value($env->{HTTP_IF_MODIFIED_SINCE});
}

sub _value {
    my $str = shift;
    # IE sends wrong formatted value(i.e. "Thu, 03 Dec 2009 01:46:32 GMT; length=17936")
    $str =~ s/;.*$//;
    return $str;
}

1;

__END__

=head1 NAME

Plack::Middleware::ConditionalGET - Middleware to add "conditional", GET

=head1 SYNOPSIS

  builder {
      enable "Plack::Middleware::ConditionalGET";
      ....
  };

=head1 DESCRIPTION

This middleware enables conditional GET and HEAD using
C<If-None-Match> and C<If-Modified-Since> header. The application
should set either or both of C<Last-Modified> or C<ETag> response
headers per RFC 2616. When either of the conditions is met, the
response body is set to be zero length and the status is set to 304
Not Modified.

=head1 SEE ALSO

Rack::ConditionalGet

=cut