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

查看:19
本文介绍了如何从 Google Cloud Functions 发送压缩的 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.

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

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

这也意味着我可以通过谷歌云平台节省大量网络费用,并为数据的移动消费者更快地加载数据.

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-type发生了变化,但是响应中没有设置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 压缩的内容,客户端可以提供 'gzip' 作为 Accept-EncodingUser-Agent 请求标头.如果不存在 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 的组合使用 Cloud Functions 发送请求:

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 发送压缩的 json 响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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