用gzip压缩的Rails json响应 [英] rails json response with gzip compression
问题描述
我有一个用Rails编写的api,它在每个请求上都会以JSON响应进行响应.
I have an api written in rails which on each request responds with a JSON response.
响应可能很大,因此我需要使用gzip压缩JSON响应.
The response could be huge, so i need to compress the JSON response using gzip.
想知道如何在Rails控制器中做到这一点?
Wondering how to do this in rails controller?
我已经添加了行
use Rack::Deflater
在config.ru
in config.ru
我还应该在呈现JSON的行中更改某些内容吗?
Should I also be changing something in the line which renders JSON?
render :json => response.to_json()
此外,我如何检查响应是否为gzip格式.
Also, how do i check if the response is in gzip format or not..??
我从终端发出了curl请求,我只看到普通的普通JSON.
I did a curl request from terminal, I see only the normal plain JSON.
推荐答案
对于响应采用gzip格式,我们不必更改render
方法调用.
如果请求的标题为Accept-Encoding: gzip
,Rails将使用gzip自动压缩JSON响应.
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()
这篇关于用gzip压缩的Rails json响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!