How to use Dart http_server:VirtualDirectory

◇◆丶佛笑我妖孽 提交于 2019-11-30 04:44:29

问题


I have been using the dart:route api for serving static files but I noticed that there is a core library called http_server that contains helper classes and functions for dart:io HttpServer.

Of particular interest to me is the class VirtualDirectory which, according to the docs, takes a String Object for the static content of directory and then you call the method serve()

var virtualDirectory = new VirtualDirectory('/var/www/');
virtualDirectory.serve(new HttpServer('0.0.0.0', 8080));

This doesn't work as there is no constructor for HttpServer - at least not in current versions.

virtualDirectory.serve(HttpServer.bind('0.0.0.0', 8080));

Which is how I have been instantiating a server also fails since virtualDirectory.serve() doesn't take a Future<HttpServer> and finally:

virtualDirectory.serve(HttpServer.bind('0.0.0.0', 8080).asStream());

also fails with The argument type 'Stream' cannot be assigned to the parameter type 'Stream'

So how do I connect a VirtualDirectory to a Server? There are no examples that I can find online and the VirtualDirectory source code does not make it clear. I would RTFM if I could FTFM. Links are fine as answers.


回答1:


The VirtualDirectory can work from inside the Future returned by HttpServer.bind. You can create a static file web server by using the following five lines of code:

HttpServer.bind('127.0.0.1', 8888).then((HttpServer server) {
    VirtualDirectory vd = new VirtualDirectory('../web/');
    vd.jailRoot = false;
    vd.serve(server);
});

You can make it more sophisticated by parsing the URI and pulling out service requests prior to serving out files.

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

main() {

  handleService(HttpRequest request) {
    print('New service request');
    request.response.write('[{"field":"value"}]');
    request.response.close();
  };

  HttpServer.bind('127.0.0.1', 8888).then((HttpServer server) {
    VirtualDirectory vd = new VirtualDirectory('../web/');
    vd.jailRoot = false;
    server.listen((request) { 
      print("request.uri.path: " + request.uri.path);
      if (request.uri.path == '/services') {
        handleService(request);
      } else {
        print('File request');
        vd.serveRequest(request);
      } 
    });
  });
}


来源:https://stackoverflow.com/questions/20295603/how-to-use-dart-http-servervirtualdirectory

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!