create a http server with a custom route in ruby

To create a simple HTTP server with a custom route in Ruby, you can use the built-in WEBrick library.

main.rb
require 'webrick'

# What port to listen on
port = 8000

# Create a new server instance
server = WEBrick::HTTPServer.new(Port: port)

# Create a custom route
server.mount_proc '/custom_route' do |req, res|
  res.content_type = 'text/text'
  res.body = 'Hello, World!'
end

# Start the server
server.start
305 chars
17 lines

This code sets up a server on port 8000, and creates a custom route at /custom_route. When a request is made to that route, the server responds with a simple "Hello, World!" message. You can modify the route and response to suit your needs.

To stop the server, simply call server.shutdown.

related categories

gistlibby LogSnag