about summary refs log tree commit diff
diff options
context:
space:
mode:
authorfranck cuny <franck@lumberjaph.net>2010-02-28 11:13:51 +0100
committerfranck cuny <franck@lumberjaph.net>2010-02-28 11:13:51 +0100
commit04e29832be471d18cbde298d555a41aed7232668 (patch)
treec281731e0b8b3820e6cd2b9aa3297e58cf650f69
parentinitial commit (diff)
downloadplack-middleware-etag-04e29832be471d18cbde298d555a41aed7232668.tar.gz
add etag header to response
-rw-r--r--lib/Plack/Middleware/ETag.pm40
1 files changed, 36 insertions, 4 deletions
diff --git a/lib/Plack/Middleware/ETag.pm b/lib/Plack/Middleware/ETag.pm
index acd2b01..fbee411 100644
--- a/lib/Plack/Middleware/ETag.pm
+++ b/lib/Plack/Middleware/ETag.pm
@@ -2,26 +2,58 @@ package Plack::Middleware::ETag;
 
 use strict;
 use warnings;
+use Digest::SHA;
+
 our $VERSION = '0.01';
 
+use parent qw/Plack::Middleware/;
+
+sub call {
+    my ( $self, $env ) = @_;
+
+    my $res     = $self->app->($env);
+    my $headers = $res->[1];
+
+    $self->response_cb(
+        $res,
+        sub {
+            my $res = shift;
+            return unless defined $res->[2];
+            return
+                if ( Plack::Util::header_exists( $headers, 'ETag' )
+                || $env->{REQUEST_METHOD} ne 'GET' );
+            my $sha     = Digest::SHA->new;
+            my $content = $res->[2];
+            $sha->add(@$content);
+            Plack::Util::header_set( $headers, 'ETag', $sha->hexdigest );
+            return;
+        }
+    );
+}
+
 1;
 __END__
 
 =head1 NAME
 
-Plack::Middleware::ETag -
+Plack::Middleware::ETag - Adds automatically an ETag header.
 
 =head1 SYNOPSIS
 
-  use Plack::Middleware::ETag;
+  use Plack::Builder;
+
+  my $app = builder {
+    enable "Plack::Middleware::ETag";
+    sub {['200', ['Content-Type' => 'text/html'}, ['hello world']]};
+  };
 
 =head1 DESCRIPTION
 
-Plack::Middleware::ETag is
+Plack::Middleware::ETag adds automatically an ETag header.
 
 =head1 AUTHOR
 
-franck cuny E<lt>franck.cuny@rtgi.frE<gt>
+franck cuny E<lt>franck@lumberjaph.netE<gt>
 
 =head1 SEE ALSO