Skip to content

Commit

Permalink
Merge pull request #53 from nox7/Modify-304-caching
Browse files Browse the repository at this point in the history
Modify 304 Caching
  • Loading branch information
nox7 authored Aug 30, 2023
2 parents 33c005b + f8e46e6 commit b0ca9a8
Show file tree
Hide file tree
Showing 3 changed files with 7 additions and 8 deletions.
2 changes: 1 addition & 1 deletion example/nox-request.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@
$nox->mapExtensionToMimeType("svg", "image/svg+xml");

// Mime caches
$nox->addCacheTimeForMime("image/png", 86400 * 60);
$nox->addCacheTimeForMime("image/png", 600);
$nox->addCacheTimeForMime("image/jpeg", 86400 * 60);
$nox->addCacheTimeForMime("text/css", 86400 * 60);
$nox->addCacheTimeForMime("text/plain", 86400 * 60);
Expand Down
2 changes: 1 addition & 1 deletion example/src/HomeController.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ class HomeController extends BaseController{
* @throws ViewFileDoesNotExist
* @throws LayoutDoesNotExist
*/
#[Route("PUT", "/")]
#[Route("GET", "/")]
public function homeView(Request $request): string{
return Renderer::renderView("home.html");
}
Expand Down
11 changes: 5 additions & 6 deletions src/Router/Router.php
Original file line number Diff line number Diff line change
Expand Up @@ -79,10 +79,11 @@ public function processRequestAsStaticFile(): void{
* setting for that mime type.
*/
$cacheTime = $this->noxInstance->staticFileHandler->getCacheTimeForMime($mimeType);
header("content-type: $mimeType");
if ($cacheTime !== null) {

header(sprintf("cache-control: max-age=%d", $cacheTime));
header("Vary: If-None-Match, etag, last-modified, cache-control");
header(sprintf("cache-control: max-age=%d; must-revalidate", $cacheTime));
header("vary: *");

$lastModifiedTime = filemtime($staticFilePath);
if ($lastModifiedTime !== false){
Expand All @@ -95,17 +96,15 @@ public function processRequestAsStaticFile(): void{
// Check if the client sent an "If-None-Match" header with the same etag used above
// If so, simply respond with 304 Not Modified and exit.
// Else, don't exit
$ifNoneMatch = Request::getFirstHeaderValue("If-None-Match");
$ifNoneMatch = $this->currentRequest->getHeaderValue("If-None-Match");
if ((string) $lastModifiedTime === $ifNoneMatch){
// Etags match, no need to send file. It's not stale
// Etags match, set 304 status
http_response_code(304);
exit();
}
}
}

$fileContents = file_get_contents(realpath($staticFilePath));
header("content-type: $mimeType");
header("content-length: " . strlen($fileContents));

// Only output for GET methods and not HEAD
Expand Down

0 comments on commit b0ca9a8

Please sign in to comment.