require 'gem_plugin' require 'mongrel' begin require 'stringio' require 'zlib' COMPRESSION_DISABLED = false rescue COMPRESSION_DISABLED = true end # == HTTP Output Compression Handler Plugin # # This class is a Mongrel web server plugin to handle a # gzip/deflate response if the client supports it. # class OutputCompression < GemPlugin::Plugin "/handlers" include Mongrel::HttpHandlerPlugin def process(request, response) return if COMPRESSION_DISABLED || request.params["HTTP_ACCEPT_ENCODING"].nil? begin request.params["HTTP_ACCEPT_ENCODING"].split(/\s*,\s*/).each do |encoding| case encoding when /\Agzip\b/ strio = StringIO.new def strio.close rewind end gz = Zlib::GzipWriter.new(strio) gz.write(response.body.string) gz.close response.body = strio response.body.rewind when /\Adeflate\b/ response.body = StringIO.new(Zlib::Deflate.deflate(response.body.string)) response.body.rewind when /\Aidentity\b/ # do nothing for identity else next # the encoding is not supported, try the next one end @content_type = encoding break # the encoding is supported, stop end response.header['Content-Encoding'] = @content_type # if response.header['Vary'] != '*' # head['Vary'] = response.header['Vary'].to_s.split(',').push('Accept-Encoding').uniq.join(',') # end STDERR.puts "Response body was encoded with #{@content_type}\n" rescue Exception => e STDERR.puts "Error with HTTP Compression: #{e.to_s}\n" response.start(500, true) do |head, out| out.write "error proceessing #{request.params['REQUEST_PATH']}\n" end end end end