I'm looking for guidance on how to improve this file server.
Currently it can't handle POSTs because each request is handed off to the http_server
lib. It also routes URLs naively; can this be improved using Router
s? Maybe the path
lib can help, too?
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);
}