Context in Ruby
Here’s the translation of the Go code to Ruby, 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 context for controlling cancellation. Ruby doesn’t have a built-in Context
object like Go, but we can achieve similar functionality using threads and timeouts.
In this Ruby version:
We use the
webrick
library to create a simple HTTP server.We define a
HelloHandler
class that inherits fromWEBrick::HTTPServlet::AbstractServlet
. This is similar to thehello
function in the original example.Inside the
do_GET
method (which is called for GET requests), we useTimeout.timeout
to simulate the context’s cancellation functionality. This will raise aTimeout::Error
if the operation takes longer than 10 seconds.We use
puts
for logging, which is similar tofmt.Println
in the original example.If a timeout occurs, we set the response status to 500 (Internal Server Error) and provide an error message.
In the main part of the script, we create a
WEBrick::HTTPServer
, mount ourHelloHandler
on the “/hello” route, and start the server.We use
trap('INT')
to handle Ctrl+C (SIGINT) and shutdown the server gracefully.
To run the server:
To test the server, you can use curl
in another terminal:
If you wait for the full 10 seconds, you’ll get the “hello” response. If you interrupt the curl command before 10 seconds (with Ctrl+C), you’ll see the timeout error message in the server logs.
This Ruby implementation provides similar functionality to the original example, demonstrating how to handle long-running operations and cancellation in an HTTP server context.