Committer: wisest-owl
LJSUP-11615. Add gzip enable for jsonU trunk/cgi-bin/LJ/Response/JSON.pm U trunk/cgi-bin/LJ/Response.pm
Modified: trunk/cgi-bin/LJ/Response/JSON.pm =================================================================== --- trunk/cgi-bin/LJ/Response/JSON.pm 2012-06-09 07:07:09 UTC (rev 12094) +++ trunk/cgi-bin/LJ/Response/JSON.pm 2012-06-09 11:16:55 UTC (rev 12095) @@ -7,6 +7,10 @@ use base qw( LJ::Response ); __PACKAGE__->mk_accessors( qw( data callback ) ); +sub content_type { + return 'application/json; charset=utf-8'; +} + sub output { my ($self) = @_; @@ -15,11 +19,14 @@ LJ::Request->send_cookies; if ($self->data) { - LJ::Request->content_type('application/json; charset=utf-8'); - my $output = LJ::JSON->to_json( $self->data ); + LJ::Request->content_type($self->content_type); + my $output = $self->do_gzip (LJ::JSON->to_json( $self->data )); + LJ::Request->header_out("Content-length", length $output); + LJ::Request->send_http_header(); if ($self->callback) { - LJ::Request->print($self->callback . "($output)"); - } else { + $output = $self->callback . "($output)"; + } + unless (LJ::Request->header_only) { LJ::Request->print($output); } } Modified: trunk/cgi-bin/LJ/Response.pm =================================================================== --- trunk/cgi-bin/LJ/Response.pm 2012-06-09 07:07:09 UTC (rev 12094) +++ trunk/cgi-bin/LJ/Response.pm 2012-06-09 11:16:55 UTC (rev 12095) @@ -38,4 +38,43 @@ return &LJ::Request::OK; } +sub content_type { + my $self = shift; + + return 'text/html; charset=utf-8'; +} + +sub do_gzip { + my $self = shift; + my $content = shift; + + ## GZIP encoding + ## 1. should we comress response? + my $do_gzip = $LJ::DO_GZIP && $LJ::OPTMOD_ZLIB; + my $length = length($content); + if (LJ::Request->header_in("X-Accept-Encoding") =~ m/gzip/){ + ## X-Accept-Encoding strictly demands gzip encoding + ## no other measurements + $do_gzip = 1; + } elsif ($do_gzip) { + ## other weighing + my $ctbase = $self->content_type; + $ctbase =~ s/;.*//; + $do_gzip = 0 unless $LJ::GZIP_OKAY{$ctbase}; + $do_gzip = 0 if LJ::Request->header_in("Accept-Encoding") !~ /gzip/; + + $do_gzip = 0 if $length < 500; + } + + ## 2. perform compression + if ($do_gzip) { + my $pre_len = $length; + LJ::Request->notes("bytes_pregzip" => $pre_len); + $content = Compress::Zlib::memGzip($content); + LJ::Request->header_out('Content-Encoding', 'gzip'); + } + + return $content; +} + 1;