我正在寻找有关如何改进此文件服务器的指导。
目前它无法处理POST,因为每个请求都会传递给http_server
lib。它还天真地路由URL;可以使用Router
来改善吗?也许path
lib也有帮助吗?
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);
}
答案 0 :(得分:1)
我没有看到解决方法
await for (var req in server) {
// distribute requests to different handlers
if(req.method == 'POST') {
} else {
publicDir.serveRequest(req);
}
}
或者,您可以将shelf
包与shelf_route
和shelf_static
一起使用,这样可以让您以更具声明性的方式分配请求和处理程序,但在引擎盖下执行相同操作
答案 1 :(得分:0)
shelf_static非常适合文件服务器,带路由的服务器可以使用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);
}