+ return NewHandler(
+ 'HTML::Mason::CGIHandler',
+ out_method => sub {
+ my $m = HTML::Mason::Request->instance;
+ my $r = $m->cgi_request;
+
+ # Send headers if they have not been sent by us or by user.
+ $r->send_http_header unless $r->http_header_sent;
+
+ # Set up a default
+ $r->content_type('text/html; charset=utf-8')
+ unless $r->content_type;
+
+ if ( $r->content_type =~ /charset=([\w-]+)$/ ) {
+ my $enc = $1;
+ if ( lc $enc !~ /utf-?8$/ ) {
+ for my $str (@_) {
+ next unless $str;
+
+ # only encode perl internal strings
+ next unless utf8::is_utf8($str);
+ $str = Encode::encode( $enc, $str );
+ }
+ }
+ }
+
+ # default to utf8 encoding
+ for my $str (@_) {
+ next unless $str;
+ next unless utf8::is_utf8($str);
+ $str = Encode::encode( 'utf8', $str );
+ }
+
+ # We could perhaps install a new, faster out_method here that
+ # wouldn't have to keep checking whether headers have been
+ # sent and what the $r->method is. That would require
+ # additions to the Request interface, though.
+ print STDOUT grep {defined} @_;
+ },
+ @_
+ );