serve method

Future<void> serve(
  1. HttpRequest request
)

Implementation

Future<void> serve(HttpRequest request) async {
  String? path;

  final uri = request.requestedUri.path.substring(1);
  if (uri.isEmpty || uri.endsWith('/')) {
    path = Path.join(this.path, uri, 'index.html');
  } else {
    path = Path.join(this.path, uri);
  }

  var file = fs.file(path);
  final response = request.response;

  if (!await file.exists()) {
    // TODO: Return 404 page when files doesn't exists.

    path = Path.join(this.path, uri, 'index.html');

    file = fs.file(path);
    if (!await file.exists()) {
      response.statusCode = HttpStatus.notFound;
      await response.close();
      return;
    }
  }

  final extension = Path.extension(path);
  final mime = _getMimeType(extension);
  response.headers.set('Content-Type', '$mime; charset=UTF-8');
  await response.addStream(file.openRead());
  await response.close();
}