Skip to content

Instantly share code, notes, and snippets.

@joecohens
Created January 9, 2018 01:37
Show Gist options
  • Save joecohens/02696d774a86d78a6003baa6c5b5418b to your computer and use it in GitHub Desktop.
Save joecohens/02696d774a86d78a6003baa6c5b5418b to your computer and use it in GitHub Desktop.
Etags middleware for Laravel
<?php
namespace App\Http\Middleware;
use Closure;
class ETags
{
/**
* Implement Etag support.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
*
* @return mixed
*/
public function handle($request, Closure $next)
{
// Get response
$response = $next($request);
// If this was a GET request...
if ($request->isMethod('get')) {
// Generate Etag
$etag = md5($response->getContent());
$requestEtag = str_replace('"', '', $request->getETags());
$requestEtag = str_replace('W/', '', $requestEtag);
// Check to see if Etag has changed
if ($requestEtag && $requestEtag[0] == $etag) {
$response->setNotModified();
}
// Set Etag
$response->setEtag($etag);
}
// Send response
return $response;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment