Http Server in Ruby
Here’s the translation of the HTTP Server example from Go to Ruby, formatted in Markdown suitable for Hugo:
Our HTTP server example demonstrates how to create a basic server using Ruby’s built-in webrick
library.
require 'webrick'
# A handler in Ruby is typically a Proc or a method that takes
# a request and a response object as arguments.
def hello(request, response)
response.body = "hello\n"
end
def headers(request, response)
# This handler reads all the HTTP request headers
# and echoes them into the response body.
response.body = request.header.map { |k, v| "#{k}: #{v.join(', ')}" }.join("\n")
end
# Create a new HTTP server on port 8090
server = WEBrick::HTTPServer.new(Port: 8090)
# Register our handlers with specific routes
server.mount_proc '/hello', method(:hello)
server.mount_proc '/headers', method(:headers)
# Start the server
puts "Server started at http://localhost:8090"
server.start
In this Ruby example, we’re using the webrick
library, which is part of Ruby’s standard library and provides a simple HTTP server implementation.
We define two handler methods: hello
and headers
. These methods take a request and a response object as arguments, similar to the handler functions in the original example.
The hello
handler simply sets the response body to “hello\n”.
The headers
handler reads all the HTTP request headers and echoes them into the response body, demonstrating a more sophisticated use of the request object.
We create a new WEBrick::HTTPServer
instance, specifying the port to listen on.
Then, we use mount_proc
to register our handlers with specific routes. This is equivalent to using http.HandleFunc
in the original example.
Finally, we start the server with server.start
. This will run the server and block the main thread until the server is stopped.
To run the server:
$ ruby http_server.rb
You can then access the server:
$ curl localhost:8090/hello
hello
$ curl localhost:8090/headers
# This will display all the headers sent in the request
This Ruby implementation provides similar functionality to the original example, demonstrating how to create a basic HTTP server with custom route handlers.