httpStaticHandler function
Sends a file of folders for a GET or HEAD request that matched no
route. true when a file was sent, false when none of the folders has
one (the caller then sends 404).
Implementation
Future<bool> httpStaticHandler(
HttpRequest req,
List<StaticFolder> folders,
) async {
List<String> segments;
try {
segments = req.uri.pathSegments;
} on FormatException {
/// `%ff` and other codes that are not UTF-8
return false;
} on ArgumentError {
return false;
}
String? host = req.headers.value(HttpHeaders.hostHeader);
for (StaticFolder folder in folders) {
if (!folder.servesHost(host)) continue;
File? file = folder.fileFor(segments);
if (file == null) continue;
if (req.response is NativeResponse) {
List<(String, String)> order = folder.precompressed
? _packedOrder(req)
: const <(String, String)>[];
FutureOr<NativeFile?> opening;
NativeFile? opened;
try {
opening = NativeFile.open(
<String>[
file.path,
for ((String, String) one in order) '${file.path}${one.$2}',
],
folder: folder.root,
request: req is NativeRequest ? req : null,
);
opened = opening is Future<NativeFile?> ? await opening : opening;
} on FileSystemException {
continue;
}
if (opened == null) continue;
String? coding;
for ((String, String) one in order) {
if (opened.path == '${file.path}${one.$2}') coding = one.$1;
}
_sendWith(
req,
file,
opened.length,
opened.modified,
folder,
coding == null ? null : File(opened.path),
coding,
opened,
);
return true;
}
/// The disk calls here are the blocking ones, like in nginx. An
/// async call of dart:io goes to another thread and back, and that
/// costs about ten times the call itself: three of them were most of
/// the time of a small file.
FileStat stat = file.statSync();
if (stat.type != FileSystemEntityType.file) continue;
/// a file that can not be read (no permission, just deleted) is a
/// 404, not a 200 with an empty body that a cache could keep
try {
file.openSync().closeSync();
} on FileSystemException {
continue;
}
_Packed? packed = folder.precompressed ? _packedFor(req, file) : null;
_send(req, file, stat, folder, packed);
return true;
}
return false;
}