handle method
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);
}
var relativePath = request.path!.remainingPath;
var 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);
}
var response = Response.notFound();
if (request.acceptsContentType(ContentType.html)) {
response
..body = "<html><h3>404 Not Found</h3></html>"
..contentType = ContentType.html;
}
return response;
}
var lastModifiedDate = file.lastModifiedSync();
var ifModifiedSince = request.raw!.headers.value(HttpHeaders.ifModifiedSinceHeader);
if (ifModifiedSince != null) {
var date = HttpDate.parse(ifModifiedSince);
if (!lastModifiedDate.isAfter(date)) {
return Response.notModified(lastModifiedDate, _policyForFile(file));
}
}
var lastModifiedDateStringValue = HttpDate.format(lastModifiedDate);
var contentType = contentTypeForExtension(path.extension(file.path)) ??
ContentType("application", "octet-stream");
var byteStream = file.openRead();
return Response.ok(byteStream,
headers: {HttpHeaders.lastModifiedHeader: lastModifiedDateStringValue})
..cachePolicy = _policyForFile(file)
..encodeBody = false
..contentType = contentType;
}