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.
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.
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);
}
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...
Look at the App Engine FAQ, specifically the answer to the question "How do I serve compressed content?":
....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...
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With