Context in TypeScript

Here’s the translation of the Go code to TypeScript, along with explanations in Markdown format suitable for Hugo:

In this example, we’ll look at setting up a simple HTTP server. HTTP servers are useful for demonstrating the usage of asynchronous programming and cancellation in TypeScript. We’ll use the http module from Node.js to create our server.

import * as http from 'http';

function hello(req: http.IncomingMessage, res: http.ServerResponse) {
    console.log("server: hello handler started");

    // Simulate some work the server is doing
    const timer = setTimeout(() => {
        res.writeHead(200, { 'Content-Type': 'text/plain' });
        res.end('hello\n');
        console.log("server: hello handler ended");
    }, 10000);

    // Handle client disconnection
    req.on('close', () => {
        clearTimeout(timer);
        console.log("server: request was cancelled");
        console.log("server: hello handler ended");
    });
}

const server = http.createServer((req, res) => {
    if (req.url === '/hello') {
        hello(req, res);
    } else {
        res.writeHead(404, { 'Content-Type': 'text/plain' });
        res.end('Not Found\n');
    }
});

server.listen(8090, () => {
    console.log('Server running on http://localhost:8090/');
});

In this TypeScript version:

  1. We import the http module from Node.js.

  2. The hello function simulates a long-running operation using setTimeout. It waits for 10 seconds before sending a response.

  3. We use the req.on('close', ...) event to handle client disconnection. This is similar to checking the context’s Done() channel in the original example.

  4. The server is created using http.createServer(), and we route the ‘/hello’ path to our hello function.

  5. Finally, we start the server listening on port 8090.

To run the server:

$ ts-node server.ts
Server running on http://localhost:8090/

Now, you can simulate a client request to /hello, and cancel it shortly after starting:

$ curl localhost:8090/hello
^C

In the server logs, you should see:

server: hello handler started
server: request was cancelled
server: hello handler ended

This demonstrates how we can handle cancellation in an asynchronous TypeScript server, similar to the context cancellation in the original example.