【问题标题】:How To Serve Files With HttpServer In Dart如何在 Dart 中使用 HttpServer 服务文件
【发布时间】:2013-11-12 16:29:11
【问题描述】:

我的 Dart 应用具有以下标准结构:

/
  pubspec.yaml
  web/
    main.css
    main.dart
    main.html
  build.dart
  server.dart

当我在服务器上收到 GET 请求时,我希望服务器使用 web 目录作为根目录并将文件内容提供给客户端。

我该怎么做?

这是我到目前为止的进展:

import 'dart:io';

void main() {
    HttpServer.bind('127.0.0.1', 80).then((HttpServer server) {
      server.listen((request) { 
        print("got request");

        switch (request.method) {
          case 'GET':
            // Do I need to send the file here? ... 
            // if not fount then send HttpStatus.NOT_FOUND;
            break;

          default:

        }
      });
    });
}

【问题讨论】:

标签: dart dart-io


【解决方案1】:

这是Matt B回答后我的代码的最新版本:

import 'dart:io';
import 'package:path/path.dart' as path;

String _basePath;

_sendNotFound(HttpResponse response) {
  response.write('Not found');
  response.statusCode = HttpStatus.NOT_FOUND;
  response.close();
}


_handleGet(HttpRequest request) {
  // PENDING: Do more security checks here?
  final String stringPath = request.uri.path == '/' ? '/main.html' : request.uri.path;
  final File file = new File(path.join(_basePath, stringPath));
  file.exists().then((bool found) {
    if (found) {
      file.openRead().pipe(request.response).catchError((e) { });
    } else {
      _sendNotFound(request.response);
    }
  });
}


_handlePost(HttpRequest request) {

}


void main() {
  _basePath = Platform.environment['HOME'];

  HttpServer.bind('127.0.0.1', 80).then((HttpServer server) {
    server.listen((request) { 
      switch (request.method) {
        case 'GET':
          _handleGet(request);
          break;

        case 'POST':
          _handlePost(request);
          break;

        default:
          request.response.statusCode = HttpStatus.METHOD_NOT_ALLOWED;
          request.response.close();
      }
    });
  });
}

【讨论】:

    【解决方案2】:

    Dart 网站在Writing web servers 上包含一个小示例,它展示了如何提供页面。在您的情况下,因为您的 server.dart 文件位于根目录中(为了将来参考,通常建议将设计为运行的 CLI 脚本保存在每个 Package Layout Conventionsbin 目录中),您将需要附加 ' web/' 到传递给脚本的参数。

    此外,请注意示例中使用的“选项”类已被弃用,您应该改用dart:io Platform.script 属性。

    也就是说,我强烈建议您考虑使用route package 来处理服务器请求,因为它可以轻松地根据匹配模式(包括请求方法)分配各种回调。

    【讨论】:

    • 暂时采用简化的方法。顺便说一句,链接示例中的 Path 类已被杀死 - 不得不使用其他东西。
    【解决方案3】:

    您要查找的内容已包含在 pub 中。

    $ pub serve --help
    
    Run a local web development server.
    
    By default, this serves "web/" and "test/", but an explicit list of 
    directories to serve can be provided as well.
    
    Usage: pub serve [directories...]
    -h, --help               Print this usage information.
        --mode               Mode to run transformers in.
                             (defaults to "debug")
    
        --all                Use all default source directories.
    -D, --define             Defines an environment constant for dart2js.
        --hostname           The hostname to listen on.
                             (defaults to "localhost")
    
        --port               The base port to listen on.
                             (defaults to "8080")
    
        --[no-]dart2js       Compile Dart to JavaScript.
                             (defaults to on)
    
        --[no-]force-poll    Force the use of a polling filesystem watcher.
    
    Run "pub help" to see global options.
    

    有关详细文档,请参阅 http://dartlang.org/tools/pub/cmd/pub-serve.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-26
      • 1970-01-01
      • 1970-01-01
      • 2019-08-09
      • 2015-09-17
      相关资源
      最近更新 更多