Context in Dart

Here’s the translation of the Go code to Dart, formatted in Markdown suitable for Hugo:

Our first example demonstrates the usage of Future and async/await in Dart, which are similar concepts to contexts in other languages for handling asynchronous operations and cancellation. Here’s the full source code:

import 'dart:async';
import 'dart:io';

Future<void> hello(HttpRequest request) async {
  print('server: hello handler started');

  try {
    await Future.delayed(Duration(seconds: 10));
    request.response
      ..write('hello\n')
      ..close();
  } catch (e) {
    print('server: $e');
    request.response
      ..statusCode = HttpStatus.internalServerError
      ..write('Internal Server Error')
      ..close();
  } finally {
    print('server: hello handler ended');
  }
}

void main() async {
  var server = await HttpServer.bind(InternetAddress.loopbackIPv4, 8090);
  print('Listening on localhost:${server.port}');

  await for (HttpRequest request in server) {
    if (request.uri.path == '/hello') {
      hello(request);
    } else {
      request.response
        ..statusCode = HttpStatus.notFound
        ..close();
    }
  }
}

In this example, we create a simple HTTP server that demonstrates how to handle asynchronous operations and potential cancellations.

The hello function is an asynchronous handler for the “/hello” route. It simulates some work by waiting for 10 seconds before sending a response. If the client disconnects before the response is sent, the Future.delayed will throw an exception, which we catch and handle.

In the main function, we set up the HTTP server and route requests to the appropriate handler.

To run the server:

$ dart run server.dart
Listening on localhost:8090

You can then simulate a client request to /hello, and interrupt it shortly after starting:

$ curl localhost:8090/hello
server: hello handler started
^C
server: HttpException: Connection closed while sending response.
server: hello handler ended

This example demonstrates how Dart handles asynchronous operations and cancellation, which is conceptually similar to the context handling in other languages.