]> git.openstreetmap.org Git - rails.git/blob - config/initializers/compressed_requests.rb
Bump qs from 6.11.0 to 6.11.1
[rails.git] / config / initializers / compressed_requests.rb
1 module OpenStreetMap
2   class CompressedRequests
3     def initialize(app)
4       @app = app
5     end
6
7     def method_handled?(env)
8       %w[POST PUT].include? env["REQUEST_METHOD"]
9     end
10
11     def encoding_handled?(env)
12       %w[gzip deflate].include? env["HTTP_CONTENT_ENCODING"]
13     end
14
15     def call(env)
16       if method_handled?(env) && encoding_handled?(env)
17         extracted = decode(env["rack.input"], env["HTTP_CONTENT_ENCODING"])
18
19         env.delete("HTTP_CONTENT_ENCODING")
20         env["CONTENT_LENGTH"] = extracted.bytesize
21         env["rack.input"] = StringIO.new(extracted)
22       end
23
24       if env["HTTP_CONTENT_ENCODING"]
25         [415, {}, []]
26       else
27         @app.call(env)
28       end
29     end
30
31     def decode(input, content_encoding)
32       input.rewind
33
34       case content_encoding
35       when "gzip" then Zlib::GzipReader.new(input).read
36       when "deflate" then Zlib::Inflate.inflate(input.read)
37       end
38     end
39   end
40 end
41
42 Rails.configuration.middleware.use OpenStreetMap::CompressedRequests