如何在Dart中使用HttpServer服务文件

时间:2013-11-12 16:29:11

标签: dart dart-io

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

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

当我在服务器上收到GET请求时,我希望服务器以root身份使用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:

        }
      });
    });
}

3 个答案:

答案 0 :(得分:5)

以下是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();
      }
    });
  });
}

答案 1 :(得分:3)

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

此外,请注意,不推荐使用示例中使用的“选项”类,而应使用dart:io Platform.script属性。

尽管如此,我强烈建议您使用route package来处理服务器请求,因为它很容易根据匹配模式(包括请求方法)分配各种回调。

答案 2 :(得分:0)

您正在寻找的内容已包含在酒吧中。

$ 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