add charset to default content-type header if STDOUT is in UTF-8
authorMischa POSLAWSKY <perl@shiar.org>
Fri, 30 May 2008 18:34:45 +0000 (18:34 +0000)
committerMischa POSLAWSKY <perl@shiar.org>
Sat, 31 May 2008 20:00:12 +0000 (20:00 +0000)
If output has utf8 layer enabled, it makes only sense to mark it as such
to clients.  Only available with PerlIO (as of Perl 5.8 afaict), but not
fatal (assume non-utf8) if it doesn't work.

Charset is only added at first read or change of the content-type value,
so it's not hardcoded to site defaults.  Requires an extra object
variable unfortunately, but the only way to make it useful (no page
runtime accomodation wouldn't give much advantage).

Changes
lib/PLP/Tie/Headers.pm

diff --git a/Changes b/Changes
index a8d2b277d0747c38c1a66dc20877dce65077230a..8d493cd57ace8b552dd080e31de6b9d3331086fc 100644 (file)
--- a/Changes
+++ b/Changes
@@ -1,3 +1,4 @@
+- Add charset to Content-Type header for UTF-8 output
 - Test pod coverage
 - %header values containing newlines will be sent as multiple fields
 - All modules use warnings and contain a $VERSION
index c675f8a128d7f8420caeb00ab6b296117bef71cb..8e023fb4fab45ce4cefb8ec8eee5dfac21b5e0ad 100644 (file)
@@ -26,12 +26,18 @@ sub TIEHASH {
                {
                        'content-type'  => 'Content-Type',
                        'x-plp-version' => 'X-PLP-Version',
-               }
+               },
+               1  # = content-type untouched
        ], $_[0];
 }
 
 sub FETCH {
        my ($self, $key) = @_;
+       if ($self->[2] and defined $self->[0]->{'Content-Type'}) {
+               my $utf8 = eval { grep {$_ eq "utf8"}  PerlIO::get_layers(*STDOUT) };
+               $self->[0]->{'Content-Type'} .= '; charset=utf-8' if $utf8;
+               $self->[2] = 0;
+       }
        $key =~ tr/_/-/;
        return $self->[0]->{ $self->[1]->{lc $key} };
 }
@@ -50,6 +56,7 @@ sub STORE {
        } else {
                $self->[1]->{lc $key} = $key;
        }
+       $self->[2] = 0 if $key eq 'Content-Type';
        return ($self->[0]->{$key} = $value);
 }