Sri Vishnu Totakura Sri Vishnu Totakura - 6 months ago 180
JSON Question

rails json response with gzip compression

I have a api written in rails which on each request response with a JSON response.,

the response is sometime huge, so i need to compress the JSON response using gzip.

How do i do this in rails controller..??

I have added the line

use Rack::Deflater


in config.ru

what should i change something in the line

render :json => response.to_json()


is that all I have to do..?
how do i check if the response is coming in gzip format or not..??

I did a curl request from my terminal, I see only the normal plain JSON itself.

Answer

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()
Comments