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:

  1. We use the webrick library to create a simple HTTP server.

  2. We define a HelloHandler class that inherits from WEBrick::HTTPServlet::AbstractServlet. This is similar to the hello function in the original example.

  3. Inside the do_GET method (which is called for GET requests), we use Timeout.timeout to simulate the context’s cancellation functionality. This will raise a Timeout::Error if the operation takes longer than 10 seconds.

  4. We use puts for logging, which is similar to fmt.Println in the original example.

  5. If a timeout occurs, we set the response status to 500 (Internal Server Error) and provide an error message.

  6. In the main part of the script, we create a WEBrick::HTTPServer, mount our HelloHandler on the “/hello” route, and start the server.

  7. 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.