Rakefile: kill raa_update task
[metropolis.git] / lib / metropolis / deflate.rb
blobc9650337dff43f5a80505bf24085b045a731ed14
1 # -*- encoding: binary -*-
2 require "zlib"
4 # allows storing pre-deflated data on disk and serving it
5 # as-is for clients that accept that deflate encoding
6 module Metropolis::Deflate
7   include Metropolis::Constants
8   Compression = "deflate"
10   def get(key, env)
11     status, headers, body = r = super
12     if 200 == status && /\bdeflate\b/ !~ env[HTTP_ACCEPT_ENCODING]
13       inflater = Zlib::Inflate.new(-Zlib::MAX_WBITS)
14       body[0] = inflater.inflate(body[0]) << inflater.finish
15       inflater.end
16       headers[Content_Length] = body[0].size.to_s
17       headers.delete(Content_Encoding)
18       headers.delete(Vary)
19     end
20     r
21   end
23   def put(key, env)
24     Wrapper.new(env) if Compression != env[HTTP_CONTENT_ENCODING]
25     super(key, env)
26   end
28   def self.extended(obj)
29     obj.instance_eval do
30       @headers[Content_Encoding] = Compression
31       @headers[Vary] = Accept_Encoding
32     end
33   end
35   class Wrapper < Metropolis::InputWrapper
37     def read_all
38       deflater = Zlib::Deflate.new(
39         Zlib::DEFAULT_COMPRESSION,
40         # drop the zlib header which causes both Safari and IE to choke
41         -Zlib::MAX_WBITS,
42         Zlib::DEF_MEM_LEVEL,
43         Zlib::DEFAULT_STRATEGY
44       )
45       deflater.deflate(@input.read) << deflater.finish
46     end
47   end
48 end