如何从Google Cloud Functions发送gzip格式的json响应? [英] How to send gzipped json response from Google Cloud Functions?

查看:177
本文介绍了如何从Google Cloud Functions发送gzip格式的json响应?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我使用gzip压缩进行响应,那么我在其中一个Google Cloud Functions中的JSON响应的大小最多可以减少70-80%.

My JSON responses in one of my Google Cloud Functions could be reduced up to 70-80% in size if I respond using gzip compression.

如何从我的函数(通过http(s)触发)发送压缩的json响应?

How can I send a compressed json response from my Functions (trigger via http(s))?

这还意味着我可以节省Google云端平台的大量网络费用,并为数据的移动用户更快地加载数据.

This would also mean I would save on a lot of network expenses with google cloud platform, and a faster loading of the data for mobile consumers of the data.

我尝试使用zlib本机模块,但是没有运气...

I've tried using the zlib native module but no luck...

if (req.get('Accept-Encoding') && req.get('Accept-Encoding').indexOf('gzip') > -1) {

    interpretation.gzip = true;

    const zlib = require('zlib');

    res.set('Content-Type', 'text/plain');
    res.set('Content-Encoding', 'gzip');

    zlib.gzip(JSON.stringify(interpretation), function (error, result) {
        if (error) throw error;
        res.status(200).send(result);
    })

} else {
    interpretation.gzip = false;
    res.status(200).send(interpretation);
}

在Postman中,响应的大小相同,内容类型已更改,但是响应中没有设置Content-Encoding标头...

In Postman, the size of the response is the same, the content-type has changed, but there is no Content-Encoding header set in the response...

推荐答案

查看 App Engine常见问题解答,特别是以下问题的答案:"我如何提供压缩内容?":

Look at the App Engine FAQ, specifically the answer to the question "How do I serve compressed content?":

....为强制提供压缩后的内容,客户可以提供"gzip"作为 Accept-Encoding 用户代理请求标头.如果没有 Accept-Encoding 标头,则永远不会压缩内容.

....To force gzipped content to be served, clients may supply 'gzip' as the value of both the Accept-Encoding and User-Agent request headers. Content will never be gzipped if no Accept-Encoding header is present...

此外,在此论坛帖子中,有一个示例如何使用Accept-EncodingUser-Agent

Also, in this group post there's an example of how to send a request with Cloud Functions using the combination of Accept-Encoding, User-Agent:

curl -v "https://us-central1-<project>.cloudfunctions.net/test" -H "User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36" -H "Accept-Encoding: gzip"

这篇关于如何从Google Cloud Functions发送gzip格式的json响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆