简体   繁体   English

如何在Laravel(Lumen)中的JSON响应中添加ETag标头

[英]How add ETag header on JSON response in Laravel (Lumen)

I have two routes: 我有两条路线:

$app->get('time1', function(){
    return response('time1 = '.time());
});
$app->get('time2', function(){
    return response()->json(['time2' => time()]);
});

And one global after-middleware: 还有一个全球性的中间件:

public function handle($request, Closure $next)
{
    $response = $next($request);
    $response->setEtag(md5($response->getContent()));
    return $response;
}

In the first case I have this HTTP-header: 在第一种情况下,我有这个HTTP标头:

ETag:"8114ac3b0aad6e54345ee00f78959316"

But not in the second. 但不是在第二个。 Why? 为什么? How to add the same header in the second case? 如何在第二种情况下添加相同的标题?

The reason you see no ETag in your second response is that this header is stripped by your web server due to the fact that the returned response is compressed by the server - see Content-Encoding: gzip header. 您在第二个响应中看不到ETag的原因是Web服务器剥离了此标头,因为服务器压缩了返回的响应 - 请参阅Content-Encoding:gzip标头。 The reasoning behind this is that the same resource cannot be byte-for-byte identical given that gzip has various compression levels . 这背后的原因是,鉴于gzip具有各种压缩级别 ,相同的资源不能逐字节相同。

You can either disable gzip compression (check your Apache config, especially config of mod_deflate module) or live without the ETag . 您可以禁用gzip压缩 (检查Apache配置,尤其是mod_deflate模块的配置),也可以不使用ETag

 ....    

  public function handle($request, Closure $next)
  {

    $response = $next($request);

    if ($request->isMethod('GET'))
    {

        $etag = md5($response->getContent());

        $requestETag = str_replace('"', '', $request->getETags());



        if ($requestETag && $requestETag[0] == $etag)
        {

            // Modifies the response so that it conforms to the rules defined for a 304 status code.
            $response->setNotModified();

        }

        $response->setETag($etag);


    }

    return $response;

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM