platform/packages/body_parser/example/main.dart

62 lines
1.6 KiB
Dart
Raw Normal View History

2017-10-12 02:32:42 +00:00
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:isolate';
2021-02-14 05:22:25 +00:00
import 'package:http_parser/http_parser.dart';
2021-06-20 13:29:23 +00:00
import 'package:angel3_body_parser/angel3_body_parser.dart';
2017-10-12 02:32:42 +00:00
2021-06-20 12:37:20 +00:00
void main() async {
2018-08-11 02:08:44 +00:00
var address = '127.0.0.1';
2017-10-12 02:32:42 +00:00
var port = 3000;
var futures = <Future>[];
2021-06-20 12:37:20 +00:00
for (var i = 1; i < Platform.numberOfProcessors; i++) {
2018-08-11 02:08:44 +00:00
futures.add(Isolate.spawn(start, [address, port, i]));
2017-10-12 02:32:42 +00:00
}
2021-06-20 12:37:20 +00:00
await Future.wait(futures).then((_) {
2017-10-12 02:32:42 +00:00
print('All instances started.');
print(
'Test with "wrk -t12 -c400 -d30s -s ./example/post.lua http://localhost:3000" or similar');
2018-08-11 02:08:44 +00:00
start([address, port, 0]);
2017-10-12 02:32:42 +00:00
});
}
void start(List args) {
2021-06-20 12:37:20 +00:00
var address = InternetAddress(args[0] as String);
var port = 8080;
2021-02-14 05:22:25 +00:00
if (args[1] is int) {
args[1];
}
2021-06-20 12:37:20 +00:00
var id = 0;
2021-02-14 05:22:25 +00:00
if (args[2] is int) {
args[2];
}
2017-10-12 02:32:42 +00:00
HttpServer.bind(address, port, shared: true).then((server) {
server.listen((request) async {
2018-08-11 02:08:44 +00:00
// ignore: deprecated_member_use
2021-02-14 05:22:25 +00:00
var body = await defaultParseBody(request);
2017-10-12 02:32:42 +00:00
request.response
2021-06-20 12:37:20 +00:00
..headers.contentType = ContentType('application', 'json')
..write(json.encode(body.body));
await request.response.close();
2017-10-12 02:32:42 +00:00
});
print(
'Server #$id listening at http://${server.address.address}:${server.port}');
});
}
2021-02-14 05:22:25 +00:00
Future<BodyParseResult> defaultParseBody(HttpRequest request,
2021-06-20 12:37:20 +00:00
{bool storeOriginalBuffer = false}) {
2021-02-14 05:22:25 +00:00
return parseBodyFromStream(
request,
request.headers.contentType != null
2021-06-20 12:37:20 +00:00
? MediaType.parse(request.headers.contentType.toString())
2021-02-14 05:22:25 +00:00
: null,
request.uri,
storeOriginalBuffer: storeOriginalBuffer);
}