How to use Dart http_server:VirtualDirectory

前端 未结 1 1031
梦毁少年i
梦毁少年i 2021-01-05 15:22

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 cl

1条回答
  •  借酒劲吻你
    2021-01-05 15:39

    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);
          } 
        });
      });
    }
    

    0 讨论(0)
提交回复
热议问题