Sha256: ce8def20a4d6daae938d5273bc87dc6132b7ebab3ed19ca514eaddd0676ed5e2

Contents?: true

Size: 1.96 KB

Versions: 1

Compression:

Stored size: 1.96 KB

Contents

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

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
mongrel_output_compression-0.1.0 lib/mongrel_output_compression/init.rb