【问题标题】:FOS Rest Bundle: Can the response be gzipped?FOS Rest Bundle:可以压缩响应吗?
【发布时间】:2019-03-04 19:24:11
【问题描述】:

我已阅读 Bundle 文档 (FOS rest-bundle),但找不到任何关于压缩响应的内容,并且我无法将压缩设置为在 Web 服务器级别发生。

有没有办法让包返回 gzip(或 deflate)压缩响应?

我目前的想法是实现一个响应侦听器,捕获它并压缩它,但我觉得可能有一个现有的方法。

编辑

我在 FOS Rest Bundle 中找不到任何启用此功能的东西 - 他们很可能希望它在服务器级别完成。解决方案是创建一个事件订阅者:

public function getSubscribedEvents() {
    return [KernelEvents::RESPONSE => ['compressResponse', -256]];
}

在我的压缩响应方法中,我对正文内容使用 deflate 并添加正确的内容编码标头:

public function compressResponse(FilterResponseEvent $event)
{
    $response = $event->getResponse();

    if ($response->headers->get('content-type') !== 'application/json') {
        return;
    }

    $response->setContent(gzdeflate($response->getContent()));
    $response->headers->set('Content-encoding', 'deflate');
}

这很好地满足了我们的目的。

【问题讨论】:

    标签: symfony fosrestbundle


    【解决方案1】:

    我们在 Apache 级别上实现了这一点,以便通过使用以下配置来启用应用程序/json 输出的网络服务器压缩。

    standard deflate conf in PHP buildpack 复制并覆盖:

    <IfModule filter_module>
       <IfModule deflate_module>
       AddOutputFilterByType DEFLATE application/json text/html text/plain text/xml text/css text/javascript application/javascript
       </IfModule>
    </IfModule>
    

    application/json 添加到此 conf 中为我们解决了问题。

    【讨论】:

    • “我无法在网络服务器级别设置压缩”。我并不是说我不能这样做。我的意思是我们不允许这样做。
    • @Erik,对不起,误解了。你认为保留这个答案是否有意义,以防有人需要这种方法?
    猜你喜欢
    • 2017-09-12
    • 2014-02-20
    • 1970-01-01
    • 2012-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-01
    • 1970-01-01
    相关资源
    最近更新 更多