use constants everywhere to reduce GC thrashing
[metropolis.git] / lib / metropolis / gzip.rb
blob98dddd6816893ba56edb472f4fda1c3f7a5a5ce4
1 # -*- encoding: binary -*-
2 require "zlib"
4 # allows storing pre-gzipped data on disk and serving it
5 # as-is for clients that accept that gzip encoding
6 module Metropolis::Gzip
7   include Metropolis::Constants
8   Compression = "gzip"
10   def get(key, env)
11     status, headers, body = r = super
12     if 200 == status && /\bgzip\b/ !~ env[HTTP_ACCEPT_ENCODING]
13       body[0] = Zlib::GzipReader.new(StringIO.new(body[0])).read
14       headers[Content_Length] = body[0].size.to_s
15       headers.delete(Content_Encoding)
16       headers.delete(Vary)
17     end
18     r
19   end
21   def put(key, env)
22     Wrapper.new(env) if Compression != env[HTTP_CONTENT_ENCODING]
23     super(key, env)
24   end
26   def self.extended(obj)
27     obj.instance_eval do
28       @headers[Content_Encoding] = Compression
29       @headers[Vary] = Accept_Encoding
30     end
31   end
33   class Wrapper < Metropolis::InputWrapper
35     def read_all
36       zipped = StringIO.new("")
37       Zlib::GzipWriter.wrap(zipped) { |io| io.write(@input.read) }
38       zipped.string
39     end
40   end
41 end