在 Dart 服务器上适当使用 'route' 和 'path' 库

Appropriate use of the 'route' and 'path' libs on a Dart server

我正在寻找有关如何改进此文件服务器的指导。

目前它无法处理 POST,因为每个请求都交给了 http_server 库。它还天真地路由 URL;可以使用 Routers 改进吗?也许 path 库也能提供帮助?

import 'dart:io';
import 'package:http_server/http_server.dart';

// TODO: use these imports :)
import 'package:path/path.dart' as path;
import 'package:route/url_pattern.dart';

final address = InternetAddress.LOOPBACK_IP_V4;
const port = 4040;

final buildPath = Platform.script.resolve('web');
final publicDir = new VirtualDirectory(buildPath.toFilePath());

main() async {
  // Override directory listing
  publicDir
    ..allowDirectoryListing = true
    ..directoryHandler = handleDir
    ..errorPageHandler = handleError;

  // Start the server
  final server = await HttpServer.bind(address, port);
  print('Listening on port $port...');
  await server.forEach(publicDir.serveRequest);
}

// Handle directory requests
handleDir(dir, req) async {
  var indexUri = new Uri.file(dir.path).resolve('index.html');
  var index = new File.fromUri(indexUri);
  if (!await index.exists()) {
    handleError(req);
    return;
  }
  publicDir.serveFile(index, req);
}

// Handle error responses
handleError(req) {
  req.response.statusCode = HttpStatus.NOT_FOUND;
  var errorUri = new Uri.directory(publicDir.root).resolve('error.html');
  var errorPage = new File.fromUri(errorUri);
  publicDir.serveFile(errorPage, req);
}

我看不出解决这个问题的方法

await for (var req in server) {
  // distribute requests to different handlers
  if(req.method == 'POST') {

  } else {
    publicDir.serveRequest(req);
  }
}

或者,您可以将 shelf 包与 shelf_routeshelf_static 一起使用,它允许您以更具声明性的方式分配请求和处理程序,但在后台执行相同的操作

https://pub.dartlang.org/search?q=shelf_static

shelf_static is excellent for file servers, and servers with routing can be done with shelf_route.

import 'dart:io';

import 'package:shelf_io/shelf_io.dart' as io;
import 'package:shelf_static/shelf_static.dart';
import 'package:path/path.dart' show join, dirname;

final address = InternetAddress.LOOPBACK_IP_V4;
const port = 8080;

main() async {
  var staticPath = join(dirname(Platform.script.toFilePath()), '..', 'web');
  var staticHandler = createStaticHandler(staticPath, defaultDocument: 'index.html');
  var server = await io.serve(staticHandler, address, port);
}