Rails Grape API 如何对结果进行 Gzip?

glorySpring · 2014年06月18日 · 最后由 glorySpring 回复于 2014年07月17日 · 2956 次阅读

我想返回压缩过的数据让客户端解压缩使用. 在没有使用 Grape 时用的 controller

response.headers['Accept-Encoding'] = "gzip"
response.headers['Content-Encoding'] = "gzip"

gzip_data = ActiveSupport::Gzip.compress(data) 

respond_to do |format|
  format.json { render json: gzip_data }
end

返回的数据接收后可以正常使用. 但是在 Grape 中没有找到任何方法可以正确返回 gzip_data.客户端没办法解析. 各位有遇见过这样的情况嘛? 求指点.......

Gzip 可以在 Nginx 上面开启

header "Content-Disposition:", " infile; filename=\"#{File.basename(file_path)}\""
content_type 'application/x-gzip'
env['api.format'] = :binary

这样?

#1 楼 @huacnlee nginx 上面已经开启了 gzip 压缩,但是在开发状态下的话 我没用 Ngxin ,用的原生的 WEBrick,这样的话测试就得自己压缩了。

#2 楼 @ruby_sky 谢谢提示,现在 ok 了。

content_type :gzip, 'application/x-gzip'
content_type :txt, 'application/txt'

加上上面两句话就可以直接使用 gzip 数据了...谢谢你们。

#3 楼 @glorySpring content_type :txt, 'application/txt' 这句干嘛的?

#4 楼 @ruby_sky 这个是他本身默认的类型..强制改了以后需要再加回来..要不然会报错...说不支持类型 'txt'

#3 楼 @glorySpring 开发环境可以用 Rack middle ware: Rack::Deflater

#6 楼 @ruby_sky 呵呵...好吧,我是个小白..哈哈

#8 楼 @glorySpring 别误会,我是指 Grape 的处理的方式怪怪的。

#10 楼 @ruby_sky 大概吧,这个我研究的少点..可能有些得方没看到,因为时间比较紧,只能这么处理了,有时间我在看下。找到合适的办法再来说说...

需要 登录 后方可回复, 如果你还没有账号请 注册新账号