【问题标题】:How do I send with brotli encoding of a Google Cloud Function HTTP response如何使用 Google Cloud Function HTTP 响应的 brotli 编码发送
【发布时间】:2019-12-22 21:20:09
【问题描述】:

如何设置内容编码作为响应?如果我设置 res.header("content-encoding", 'br') 并发送 brotli 版本

exports.helloWorld = (req, res) => {
  res.header("content-encoding", 'br')
  let message = Buffer.from('Hello World!');
  res.write(brotli.compress(message));
  res.end();
};

google 函数覆盖content-encoding 并获取值content-encoding: gzip

【问题讨论】:

  • 您必须自己执行压缩。仅设置标题不会自动按您想要的方式压缩它。
  • 是的,我用 brottli 压缩了它,但谷歌函数覆盖了内容编码,浏览器无法正确解析
  • @Tom910 你能在哪里解决这个问题?自己进行压缩并正确发送数据?如果是这样,请您分享您的答案!谢谢
  • @pagep 在这种情况下我没有找到解决方案,也没有使用谷歌功能

标签: node.js google-cloud-platform google-cloud-functions


【解决方案1】:

我认为这是不可能的,因为据此documentationNodeJS 的 Google Cloud 函数使用 Express 4 来处理 HTTP,而据此Express GitHub issue Brotli 不受支持

【讨论】:

【解决方案2】:

要将 brotli 压缩与 GCP 云函数一起使用,您必须使用 onRequest 公开快速响应的函数类型,您可以在其中更改响应标头。

import * as functions from "firebase-functions";
import * as zlib from "zlib";

const runTest = functions
  .https.onRequest(async (request, response) => {
    // Allowing CORS on my function
    response.set('Access-Control-Allow-Origin', "*")


    zlib.brotliCompress(JSON.stringify({something: "this is test"}), ((error, result) => {
      if(error){
        console.error("Error", error)
        response.status(500).end()
      }

      response.set("content-encoding", "br")
      response.send(result);
    }))
}

export { runTest };

我从 gzip 的 50kB 到 brotli 的 20kB。

但是,您还必须考虑其他问题。 Brotli 压缩对 CPU 的压缩要求更高。有不同的压缩选项,您可以考虑根据数据大小更改它们。我还没有和他们一起玩。我们也可以流式传输数据?对 express 框架进行一些调整。

编辑: 这是我的流实现,为我的用例调整了参数。 我的响应时间值与 gzip 相同,CF 性能相同,传输大小减少 40%。 (仅供参考:在调整参数之前,我的响应时间确实很慢,我认为 BROTLI_MODE_TEXT 帮助很大!)

import * as stream from "stream";

const stringifiedData = JSON.stringify(inputData);

const inputStream = new stream.Readable(); // Create the stream
inputStream.push(stringifiedData); // Push the data
inputStream.push(null); // End the stream data

const passTrough = new stream.PassThrough()

const brotli = zlib.createBrotliCompress(  {
  chunkSize: 32 * 1024,
  params: {
    [zlib.constants.BROTLI_PARAM_MODE]: zlib.constants.BROTLI_MODE_TEXT,
    [zlib.constants.BROTLI_PARAM_QUALITY]: 4,
    [zlib.constants.BROTLI_PARAM_SIZE_HINT]: stringifiedData.length
  }});

inputStream.pipe(brotli).pipe(passTrough)

passTrough.on('data', (data) => {
  response.write(data);
})

passTrough.on('end', () => {
  response.end();
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-20
    • 1970-01-01
    • 2020-08-31
    • 2020-04-14
    • 2020-09-24
    相关资源
    最近更新 更多