ResponseCache.ifModifiedSince
This commit is contained in:
parent
b64bebf18f
commit
4a8d9ee31e
2 changed files with 24 additions and 13 deletions
|
@ -1,2 +1,3 @@
|
||||||
export 'src/cache.dart';
|
export 'src/cache.dart';
|
||||||
export 'src/cache_service.dart';
|
export 'src/cache_service.dart';
|
||||||
|
export 'src/serializer.dart';
|
|
@ -14,18 +14,25 @@ class ResponseCache {
|
||||||
|
|
||||||
ResponseCache({this.timeout});
|
ResponseCache({this.timeout});
|
||||||
|
|
||||||
Future<bool> handleRequest(RequestContext req, ResponseContext res) async {
|
/// A middleware that handles requests with an `If-Modified-Since` header.
|
||||||
var now = new DateTime.now().toUtc();
|
///
|
||||||
|
/// This prevents the server from even having to access the cache, and plays very well with static assets.
|
||||||
|
Future<bool> ifModifiedSince(RequestContext req, ResponseContext res) async {
|
||||||
|
if (req.headers.value('if-modified-since') != null) {
|
||||||
|
var modifiedSince = _fmt.parse(req.headers.value('if-modified-since'));
|
||||||
|
|
||||||
// Check if there is a cache entry.
|
// Check if there is a cache entry.
|
||||||
for (var pattern in patterns) {
|
for (var pattern in patterns) {
|
||||||
if (pattern.allMatches(req.uri.path).isNotEmpty && _cache.containsKey(req.uri.path)) {
|
if (pattern.allMatches(req.uri.path).isNotEmpty &&
|
||||||
var response = _cache[req.uri.path];
|
_cache.containsKey(req.uri.path)) {
|
||||||
|
var response = _cache[req.uri.path];
|
||||||
|
|
||||||
// Only send a cached response if it is valid.
|
// Only send a cached response if it is valid.
|
||||||
if (timeout == null || now.difference(response.timestamp) >= timeout) {
|
if (timeout == null ||
|
||||||
// TODO: If-Last-Modified
|
modifiedSince.difference(response.timestamp) >= timeout) {
|
||||||
break;
|
res.statusCode = 304;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -33,7 +40,10 @@ class ResponseCache {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<bool> responseFinalizer(RequestContext req, ResponseContext res) async {
|
Future<bool> responseFinalizer(
|
||||||
|
RequestContext req, ResponseContext res) async {
|
||||||
|
if (res.statusCode == 304) return true;
|
||||||
|
|
||||||
var now = new DateTime.now().toUtc();
|
var now = new DateTime.now().toUtc();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
Loading…
Reference in a new issue