rails json response with gzip compression

一曲冷凌霜 提交于 2019-11-30 03:31:47

My post Content Compression with Rack::Deflater describes a couple of ways to integrate Rack::Deflater. The easiest would be to just update config/application.rb with:

module YourApp
  class Application < Rails::Application
    config.middleware.use Rack::Deflater
  end
end

and you'll automatically compress all controller responses with deflate / gzip if the client explicitly says they can handle it.

For the response to be in gzip format we don't have to change the render method call.
If the request has the header Accept-Encoding: gzip, Rails will automatically compress the JSON response using gzip.

If you don't want the user to send a request with preset header., you can add the header to the request manually in the controller before rendering the response:

request.env['HTTP_ACCEPT_ENCODING'] = 'gzip'
render :json => response.to_json()

You can query Curl by setting a custom header to get gzipped response

$ curl -H "Accept-Encoding: gzip, deflate" localhost:3000/posts.json > posts_json.gz

then, then decompress it to view the actual response json

 $ gzip -d posts_json.gz
 $ cat posts_json

If it doesn't work. post back with output of rake middlewares to help us troubleshoot further.

In some cases you can consider to write huge response into a file and gzip it:

res = {} # huge data hash
json = res.to_json

Zlib::GzipWriter.open('public/api/huge_data.json.gz') { |gz| gz.write json }

and update this file regularly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!