Added working ETag (304 Not Modified) support based on the final rendered HTML (Grav 1.7 edition)

This commit is contained in:
Matias Griese
2019-10-16 23:52:06 +03:00
parent e2843e6477
commit ef8e1c2fdf
4 changed files with 19 additions and 7 deletions

View File

@@ -273,9 +273,21 @@ class Grav extends Container
$debugger = $this['debugger'];
$response = $debugger->logRequest($request, $response);
// Send the response and terminate.
$body = $response->getBody();
// Handle ETag and If-None-Match headers.
if ($response->getHeaderLine('ETag') === '1') {
$etag = md5($body);
$response = $response->withHeader('ETag', $etag);
if ($request->getHeaderLine('If-None-Match') === $etag) {
$response = $response->withStatus(304);
$body = '';
}
}
$this->header($response);
echo $response->getBody();
echo $body;
exit();
}

View File

@@ -281,7 +281,7 @@ interface PageLegacyInterface
*
* @return bool show etag header
*/
public function eTag($var = null);
public function eTag($var = null): bool;
/**
* Gets and sets the path to the .md file for this Page object.

View File

@@ -1950,7 +1950,7 @@ class Page implements PageInterface
*
* @return bool show etag header
*/
public function eTag($var = null)
public function eTag($var = null): bool
{
if ($var !== null) {
$this->etag = $var;
@@ -1959,7 +1959,7 @@ class Page implements PageInterface
$this->etag = (bool)Grav::instance()['config']->get('system.pages.etag');
}
return $this->etag;
return $this->etag ?? false;
}
/**

View File

@@ -151,7 +151,7 @@ trait PageLegacyTrait
// Calculate ETag based on the serialized page and modified time.
if ($this->eTag()) {
$headers['ETag'] = '"' . md5(json_encode($this) . $this->modified()).'"';
$headers['ETag'] = '1';
}
// Set Vary: Accept-Encoding header.
@@ -675,7 +675,7 @@ trait PageLegacyTrait
'etag',
$var,
static function ($value) {
return (bool)($value ?? Grav::instance()['config']->get('system.pages.last_modified'));
return (bool)($value ?? Grav::instance()['config']->get('system.pages.etag'));
}
);
}