server.dart 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. import 'dart:convert';
  2. import 'dart:io';
  3. import 'dart:isolate';
  4. final _encoder = JsonUtf8Encoder();
  5. void main(List<String> _) async {
  6. /// Create an [Isolate] containinig an [HttpServer]
  7. /// for each processor after the first
  8. for (var i = 1; i < Platform.numberOfProcessors; i++) {
  9. await Isolate.spawn(_startServer, _);
  10. }
  11. /// Create a [HttpServer] for the first processor
  12. await _startServer(_);
  13. }
  14. /// Creates and setup a [HttpServer]
  15. Future<void> _startServer(List<String> _) async {
  16. /// Binds the [HttpServer] on `0.0.0.0:8080`.
  17. final server = await HttpServer.bind(
  18. InternetAddress('0.0.0.0', type: InternetAddressType.IPv4),
  19. 8080,
  20. shared: true,
  21. );
  22. /// Sets [HttpServer]'s [serverHeader].
  23. server
  24. ..defaultResponseHeaders.clear()
  25. ..serverHeader = 'dart';
  26. /// Handles [HttpRequest]'s from [HttpServer].
  27. await for (final request in server) {
  28. switch (request.uri.path) {
  29. case '/json':
  30. _jsonTest(request);
  31. break;
  32. case '/plaintext':
  33. _plaintextTest(request);
  34. break;
  35. default:
  36. _sendResponse(request, HttpStatus.notFound);
  37. }
  38. }
  39. }
  40. /// Completes the given [request] by writing the [bytes] with the given
  41. /// [statusCode] and [type].
  42. void _sendResponse(
  43. HttpRequest request,
  44. int statusCode, {
  45. ContentType? type,
  46. List<int> bytes = const [],
  47. }) =>
  48. request.response
  49. ..statusCode = statusCode
  50. ..headers.contentType = type
  51. ..headers.date = DateTime.now()
  52. ..contentLength = bytes.length
  53. ..add(bytes)
  54. ..close();
  55. /// Completes the given [request] by writing the [response] as JSON.
  56. void _sendJson(HttpRequest request, Object response) => _sendResponse(
  57. request,
  58. HttpStatus.ok,
  59. type: ContentType.json,
  60. bytes: _encoder.convert(response),
  61. );
  62. /// Completes the given [request] by writing the [response] as plain text.
  63. void _sendText(HttpRequest request, String response) => _sendResponse(
  64. request,
  65. HttpStatus.ok,
  66. type: ContentType.text,
  67. bytes: utf8.encode(response),
  68. );
  69. /// Responds with the JSON test to the [request].
  70. void _jsonTest(HttpRequest request) => _sendJson(
  71. request,
  72. const {'message': 'Hello, World!'},
  73. );
  74. /// Responds with the plaintext test to the [request].
  75. void _plaintextTest(HttpRequest request) => _sendText(
  76. request,
  77. 'Hello, World!',
  78. );