HttpStaticRoute constructor

HttpStaticRoute(
  1. String path, {
  2. required String directoryPath,
  3. Set<String> methods = const {'GET'},
  4. List<HttpController>? controllers,
  5. String? defaultDocument,
  6. bool listDirectory = false,
})

Implementation

HttpStaticRoute(
  super.path, {
  required String directoryPath,
  super.methods = const {'GET'},
  super.controllers,
  String? defaultDocument,
  bool listDirectory = false,
}) : super(
        handler: (request, payload) {
          final dir = Directory(directoryPath);

          var fileName = request.uri.path.substring(path.length);

          if (fileName.startsWith('/')) {
            fileName = fileName.substring(1);
          }

          if (fileName.isEmpty) {
            if (defaultDocument != null) {
              fileName = defaultDocument;
            }

            /// ls
            else if (listDirectory) {
              final files = dir.listSync().where((element) {
                return element.statSync().type == FileSystemEntityType.file;
              });

              final content = [
                for (final element in files)
                  '$path/${element.path.split('/').last}',
              ];

              request.response.ok(
                body: _getListDirectoryHtml(content),
                contentType: ContentType.html,
              );
              return;
            }
          }

          final file = File('${dir.path}/$fileName');

          if (!file.existsSync()) {
            request.response.notFound();
            return;
          }

          final mimeType = lookupMimeType('${dir.path}/$fileName');

          if (mimeType == null) {
            request.response.internalServerError(
              message: 'Mime-Type not found',
            );
            return;
          }

          final bytes = file.readAsBytesSync();

          request.response.headers.contentLength = bytes.length;
          request.response.headers.contentType = ContentType.parse(mimeType);

          request.response.add(file.readAsBytesSync());
          request.response.close();
        },
      );