这是 Dart 为使用
Shelf
包的服务器提供的典型代码:
import 'dart:io';
import 'package:shelf/shelf.dart';
import 'package:shelf/shelf_io.dart';
import 'package:shelf_router/shelf_router.dart';
// Configure routes.
final _router = Router()
..get('/', _rootHandler)
..get('/echo/<message>', _echoHandler);
Response _rootHandler(Request req) {
return Response.ok('Hello, World!\n');
}
Response _echoHandler(Request request) {
final message = request.params['message'];
return Response.ok('$message\n');
}
void main(List<String> args) async {
// Use any available host or container IP (usually `0.0.0.0`).
final ip = InternetAddress.anyIPv4;
// Configure a pipeline that logs requests.
final _handler = Pipeline().addMiddleware(logRequests()).addHandler(_router);
// For running in containers, we respect the PORT environment variable.
final port = int.parse(Platform.environment['PORT'] ?? '8080');
final server = await serve(_handler, ip, port);
print('Server listening on port ${server.port}');
}
需要修改什么/如何才能支持安全连接 (HTTPS) 仅?
我不太了解证书,所以如果您能详细解释如何生成/购买它们以及如何将它们链接到服务器或任何傻瓜参考,那就太好了。
P.S.:我的主机是运行以下 Docker 容器的 Linux 发行版 (Manjaro):文件服务器 (Dart with Shelf) 和 GraphQL 服务器 (Postgraphile)。我需要为主机中运行的每个服务进行配置吗?
首先,我感谢@KevinMoore的回答,但它并不像我希望的那样完整,所以这就是我的答案:
根据Dart帮助将上面的代码修改为这样:
import 'dart:io';
import 'package:shelf/shelf.dart';
import 'package:shelf/shelf_io.dart';
import 'package:shelf_router/shelf_router.dart';
// Configure routes.
final _router = Router()
..get('/', _rootHandler)
..get('/echo/<message>', _echoHandler);
Response _rootHandler(Request req) {
return Response.ok('Hello, World!\n');
}
Response _echoHandler(Request request) {
final message = request.params['message'];
return Response.ok('$message\n');
}
SecurityContext getSecurityContext() { // Bind with a secure HTTPS connection
final chain = Platform.script.resolve('certificates/server_chain.pem').toFilePath();
final key = Platform.script.resolve('certificates/server_key.pem').toFilePath();
return SecurityContext()
..useCertificateChain(chain)
..usePrivateKey(key, password: 'dartdart');
}
void main(List<String> args) async {
// Use any available host or container IP (usually `0.0.0.0`).
final ip = InternetAddress.anyIPv4;
// Configure a pipeline that logs requests.
final _handler = Pipeline().addMiddleware(logRequests()).addHandler(_router);
// For running in containers, we respect the PORT environment variable.
final port = int.parse(Platform.environment['PORT'] ?? '443');
final server = await serve(_handler, ip, port, securityContext: getSecurityContext());
print('Server listening on port ${server.port}');
}
对于该代码,我使用 Dart 团队在其存储库中提供的证书和密码,仅用于教育目的。
如果您的生产环境中的服务器需要证书,您可以通过 Let's Encrypt 免费获取它们。
这些视频对于如何获取和使用这些证书很有用:
这个教程(日文)也是一个很好的参考。
你见过https://api.dart.dev/dev/2.16.0-7.0.dev/dart-io/HttpServer-class.html吗?
您可以将
HttpServer
实例传递给 pkg:shelf 中的 serveRequests
(https://pub.dev/documentation/shelf/latest/shelf_io/serveRequests.html)