handle method

  1. @override
Future<RequestOrResponse> handle(
  1. Request request
)
override

The primary request handling method of this object.

Subclasses implement this method to provide their request handling logic.

If this method returns a Response, it will be sent as the response for request linked controllers will not handle it.

If this method returns request, the linked controller handles the request.

If this method returns null, request is not passed to any other controller and is not responded to. You must respond to request through Request.raw.

Implementation

@override
Future<RequestOrResponse> handle(Request request) async {
  if (request.method != "GET") {
    return Response(HttpStatus.methodNotAllowed, null, null);
  }

  final relativePath = request.path.remainingPath;
  final fileUri = _servingDirectory.resolve(relativePath ?? "");
  File file;
  if (FileSystemEntity.isDirectorySync(fileUri.toFilePath())) {
    file = File.fromUri(fileUri.resolve("index.html"));
  } else {
    file = File.fromUri(fileUri);
  }

  if (!file.existsSync()) {
    if (_onFileNotFound != null) {
      return _onFileNotFound(this, request);
    }

    final response = Response.notFound();
    if (request.acceptsContentType(ContentType.html)) {
      response
        ..body = "<html><h3>404 Not Found</h3></html>"
        ..contentType = ContentType.html;
    }
    return response;
  }

  final lastModifiedDate = file.lastModifiedSync();
  final ifModifiedSince =
      request.raw.headers.value(HttpHeaders.ifModifiedSinceHeader);
  if (ifModifiedSince != null) {
    final date = HttpDate.parse(ifModifiedSince);
    if (!lastModifiedDate.isAfter(date)) {
      return Response.notModified(lastModifiedDate, _policyForFile(file));
    }
  }

  final lastModifiedDateStringValue = HttpDate.format(lastModifiedDate);
  final contentType = contentTypeForExtension(path.extension(file.path)) ??
      ContentType("application", "octet-stream");
  final byteStream = file.openRead();

  return Response.ok(
    byteStream,
    headers: {HttpHeaders.lastModifiedHeader: lastModifiedDateStringValue},
  )
    ..cachePolicy = _policyForFile(file)
    ..encodeBody = false
    ..contentType = contentType;
}