create a http server on a specific port and host in ruby

To create an HTTP server on a specific port and host in Ruby, you can use the built-in WEBrick library. Here's an example:

main.rb
require 'webrick'

# Set the options hash with the desired host and port
options = {
  Port: 8080,
  BindAddress: 'localhost'
}

# Create a new server using the options hash
server = WEBrick::HTTPServer.new(options)

# Set up a handler for incoming requests
server.mount_proc '/' do |req, res|
  res.body = 'Hello, world!'
end

# Start the server
server.start
360 chars
19 lines

In this example, we set the Port option to 8080 and the BindAddress option to 'localhost'. We then create a new instance of WEBrick::HTTPServer using these options. We set up a handler for incoming requests by calling server.mount_proc and passing a block that sets the response body to 'Hello, world!'. Finally, we start the server by calling server.start.

You can access the server by visiting http://localhost:8080 in your web browser or using a tool like curl to send a request to the server.

related categories

gistlibby LogSnag