handleRequest method

Future<bool> handleRequest(
  1. RequestContext req,
  2. ResponseContext res
)

Serves content from the cache, if applicable.

Implementation

Future<bool> handleRequest(RequestContext req, ResponseContext res) async {
  if (!await ifModifiedSince(req, res)) return false;
  if (req.method != 'GET' && req.method != 'HEAD') return true;
  if (!res.isOpen) return true;

  // Check if there is a cache entry.
  //
  // If `if-modified-since` is present, this check has already been performed.
  if (req.headers?.ifModifiedSince == null) {
    for (var pattern in patterns) {
      if (pattern.allMatches(_getEffectivePath(req)).isNotEmpty) {
        var now = DateTime.now().toUtc();

        if (_cache.containsKey(_getEffectivePath(req))) {
          var response = _cache[_getEffectivePath(req)];

          if (response == null ||
              now.difference(response.timestamp) >= timeout) {
            return true;
          }

          _setCachedHeaders(response.timestamp, req, res);
          res
            ..headers.addAll(response.headers)
            ..add(response.body);
          await res.close();
          return false;
        } else {
          _setCachedHeaders(now, req, res);
        }
      }
    }
  }

  return true;
}