httpStaticHandler function

Future<bool> httpStaticHandler(
  1. HttpRequest req,
  2. List<StaticFolder> folders
)

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;
    FileStat stat = await file.stat();
    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 {
      await (await file.open()).close();
    } on FileSystemException {
      continue;
    }
    _send(req, file, stat, folder.maxAge);
    return true;
  }
  return false;
}