Context in Elixir
Here’s the translation of the Go code to Elixir, 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 processes for controlling cancellation. In Elixir, we use processes and message passing to handle concurrency and cancellation, which is similar to the concept of context.Context
in other languages.
In this Elixir code:
We define an
Application
module that starts a Cowboy server with ourRouter
module.In the
Router
module, we define a/hello
route that simulates a long-running operation.We use
Task.async
to start a process that sleeps for 10 seconds, simulating work.We use
receive
to wait for either the task to complete or an exit signal.If the task completes, we send a success response. If we receive an exit signal (simulating cancellation), we send an error response.
We also have a timeout of 11 seconds, after which we shut down the task and send a timeout response.
To run the server:
To simulate a client request to /hello
, hitting Ctrl+C shortly after starting to signal cancellation:
This example demonstrates how Elixir handles concurrent operations and cancellation using processes and message passing, which is conceptually similar to using contexts for cancellation in other languages.