Context in Haskell
Here’s the translation of the Go code to Haskell, 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 cancellation control. In Haskell, we can use the async
library for handling cancellation and timeouts.
In this Haskell version:
We use the
wai
andwarp
libraries to create a simple HTTP server.The
hello
function is our request handler. It simulates work by waiting for 10 seconds before responding.We use the
race
function from theasync
library to implement a timeout. This is similar to theselect
statement in the original Go code.If the delay completes before cancellation, we send a “hello” response. If cancellation occurs first, we send an error response.
In the
main
function, we start the server on port 8090.
To run the server:
To simulate a client request to /hello
, hitting Ctrl+C shortly after starting to signal cancellation:
Note that Haskell doesn’t have a built-in concept directly equivalent to Go’s context.Context
. The async
library provides similar functionality for handling cancellation and timeouts in concurrent operations.