Here’s the translation of the Go code to Scala, along with explanations in Markdown format suitable for Hugo:
In the previous example we looked at setting up a simple HTTP server. HTTP servers are useful for demonstrating the usage of cancellation control. In Scala, we can use Future for handling asynchronous operations and Promise for cancellation signals.
In this Scala example, we’re using Akka HTTP to set up a simple HTTP server. The hello function defines a route that simulates some work by sleeping for 10 seconds before responding.
We use a Promise to represent a cancellation signal. This is passed to the hello function, allowing us to cancel the operation from outside.
The Future.firstCompletedOf is used to race between the actual work, a timeout, and the cancellation signal. Whichever completes first will determine the response.
To run the server:
Simulate a client request to /hello, hitting Ctrl+C shortly after starting to signal cancellation:
This example demonstrates how to handle long-running operations in a web server context, with the ability to cancel operations and handle timeouts. While Scala doesn’t have a direct equivalent to Go’s context.Context, we can achieve similar functionality using Futures and Promises.