]> Sergey Matveev's repositories - public-inbox.git/blobdiff - lib/PublicInbox/WwwStatic.pm
wwwstatic: implement Last-Modified and If-Modified-Since
[public-inbox.git] / lib / PublicInbox / WwwStatic.pm
index 76e50c789b7336a653e99de9e46afbe67dee9203..b8efcf625a184d03507161f570787f4547032f7a 100644 (file)
@@ -4,6 +4,7 @@
 package PublicInbox::WwwStatic;
 use strict;
 use Fcntl qw(:seek);
+use HTTP::Date qw(time2str);
 
 sub prepare_range {
        my ($env, $in, $h, $beg, $end, $size) = @_;
@@ -50,9 +51,14 @@ sub response {
        my ($env, $h, $path, $type) = @_;
        return unless -f $path && -r _; # just in case it's a FIFO :P
 
-       # TODO: If-Modified-Since and Last-Modified?
        open my $in, '<', $path or return;
        my $size = -s $in;
+       my $mtime = time2str((stat(_))[9]);
+
+       if (my $ims = $env->{HTTP_IF_MODIFIED_SINCE}) {
+               return [ 304, [], [] ] if $mtime eq $ims;
+       }
+
        my $len = $size;
        my $code = 200;
        push @$h, 'Content-Type', $type;
@@ -63,7 +69,7 @@ sub response {
                        return [ 416, $h, [] ];
                }
        }
-       push @$h, 'Content-Length', $len;
+       push @$h, 'Content-Length', $len, 'Last-Modified', $mtime;
        my $body = bless {
                initial_rd => 65536,
                len => $len,
@@ -77,25 +83,23 @@ sub response {
 # called by PSGI servers:
 sub getline {
        my ($self) = @_;
-       my $len = $self->{len};
-       return if $len == 0;
+       my $len = $self->{len} or return; # undef, tells server we're done
        my $n = delete($self->{initial_rd}) // 8192;
        $n = $len if $len < $n;
        my $r = sysread($self->{in}, my $buf, $n);
-       if (!defined $r) {
-               $self->{env}->{'psgi.errors'}->print(
-                       "$self->{path} read error: $!\n");
-       } elsif ($r > 0) { # success!
+       if (defined $r && $r > 0) { # success!
                $self->{len} = $len - $r;
                return $buf;
-       } else {
-               $self->{env}->{'psgi.errors'}->print(
-                       "$self->{path} EOF with $len bytes left\n");
        }
+       my $m = defined $r ? "EOF with $len bytes left" : "read error: $!";
+       my $env = $self->{env};
+       $env->{'psgi.errors'}->print("$self->{path} $m\n");
 
        # drop the client on error
-       if (my $io = $self->{env}->{'psgix.io'}) {
-               $io->close; # this is PublicInbox::DS::close
+       if (my $io = $env->{'psgix.io'}) {
+               $io->close; # this is likely PublicInbox::DS::close
+       } else { # for some PSGI servers w/o psgix.io
+               die "dropping client socket\n";
        }
        undef;
 }