return a html response from a http server in ruby

You can return a HTML response in Ruby using the WEBrick module. Here's an example code block:

main.rb
require 'webrick'
 
server = WEBrick::HTTPServer.new(:Port => 8000)
 
server.mount_proc('/') do |req, res|
  res.body = '<html><body><h1>Hello, World!</h1></body></html>'
end
 
trap('INT') { server.shutdown }
 
server.start
224 chars
12 lines

In this code block, we create and start the HTTP server on port 8000. When a request is made to the root directory (/), we set the response body to a basic HTML document containing a heading with the text "Hello, World!". Finally, we gracefully shut down the server when interrupt signal is received.

This is a simple example, but you can customize the response to include any content you want within the HTML body.

related categories

gistlibby LogSnag