Class: OutputCompression

Inherits:
Object
  • Object
show all
Includes:
Mongrel::HttpHandlerPlugin
Defined in:
lib/mongrel_output_compression/init.rb

Overview

HTTP Output Compression Handler Plugin

This class is a Mongrel web server plugin to handle a gzip/deflate response if the client supports it.

Instance Method Summary collapse

Instance Method Details

#process(request, response) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/mongrel_output_compression/init.rb', line 20

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