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.
require 'webrick'
require 'timeout'
class HelloHandler < WEBrick::HTTPServlet::AbstractServlet
def do_GET(request, response)
puts "server: hello handler started"
begin
Timeout.timeout(10) do
# Simulate some work
sleep 10
response.body = "hello\n"
end
rescue Timeout::Error
puts "server: request timed out"
response.status = 500
response.body = "Internal Server Error: Request timed out"
end
puts "server: hello handler ended"
end
end
server = WEBrick::HTTPServer.new(Port: 8090)
server.mount "/hello", HelloHandler
trap('INT') { server.shutdown }
server.start
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:
$ ruby context.rb
To test the server, you can use curl
in another terminal:
$ curl localhost:8090/hello
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.