我的Dart应用程序有以下标准结构:
/
pubspec.yaml
web/
main.css
main.dart
main.html
build.dart
server.dart
Run Code Online (Sandbox Code Playgroud)
当我在服务器上收到GET请求时,我希望服务器以web
root 身份使用该目录,并将文件内容提供给客户端.
我怎样才能做到这一点?
这是到目前为止我已经走了多远:
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:
}
});
});
}
Run Code Online (Sandbox Code Playgroud)
这是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();
}
});
});
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2149 次 |
最近记录: |