-
Notifications
You must be signed in to change notification settings - Fork 2k
/
server.dart
88 lines (78 loc) · 2.25 KB
/
server.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
import 'dart:async' show Future;
import 'dart:convert';
import 'dart:io';
import 'dart:isolate';
final _procNumber = Platform.numberOfProcessors;
final _encoder = JsonUtf8Encoder();
void main(List<String> args) {
var errorPort = ReceivePort();
errorPort.listen((e) => print(e));
for (var i = 1; i < _procNumber; i++) {
Isolate.spawn(_startInIsolate, [], onError: errorPort.sendPort);
}
_startInIsolate([]);
}
void _startInIsolate(List args) {
_startServer();
}
Future<void> _startServer() async {
final server = await HttpServer.bind('0.0.0.0', 8080, shared: true);
server.defaultResponseHeaders.clear();
server.serverHeader = 'dart';
server.listen((request) {
switch (request.uri.path) {
case '/json':
_jsonTest(request);
break;
case '/plaintext':
_plaintextTest(request);
break;
default:
_sendResponse(request, HttpStatus.notFound);
break;
}
});
}
/// Completes the given [request] by writing the [bytes] with the given
/// [statusCode] and [type].
void _sendResponse(
HttpRequest request,
int statusCode, {
ContentType? type,
List<int>? bytes,
}) {
final response = request.response;
response
..statusCode = statusCode
..headers.date = DateTime.now();
if (type != null) {
response.headers.contentType = type;
}
if (bytes != null) {
response
..contentLength = bytes.length
..add(bytes);
} else {
response.contentLength = 0;
}
response.close();
}
/// Completes the given [request] by writing the [response] as JSON.
void _sendJson(HttpRequest request, Object response) => _sendResponse(
request,
HttpStatus.ok,
type: ContentType.json,
bytes: _encoder.convert(response),
);
/// Completes the given [request] by writing the [response] as plain text.
void _sendText(HttpRequest request, String response) => _sendResponse(
request,
HttpStatus.ok,
type: ContentType.text,
bytes: utf8.encode(response),
);
/// Responds with the JSON test to the [request].
void _jsonTest(HttpRequest request) =>
_sendJson(request, const {'message': 'Hello, World!'});
/// Responds with the plaintext test to the [request].
void _plaintextTest(HttpRequest request) => _sendText(request, 'Hello, World!');