create a http server and add a custom header to the response in ruby

To create a HTTP server in Ruby, you can use the built-in WEBrick library. Here's an example code snippet that creates a basic HTTP server that listens on port 8000 and returns a plain text response "Hello, world!" with a custom "X-Custom-Header" header:

main.rb
require 'webrick'

server = WEBrick::HTTPServer.new(Port: 8000)

server.mount_proc '/' do |req, res|
  res['X-Custom-Header'] = 'Custom header value'
  res.content_type = 'text/plain'
  res.body = 'Hello, world!'
end

server.start
231 chars
12 lines

In this example, we use the WEBrick::HTTPServer class to create a new server instance listening on port 8000. We then use the mount_proc method to specify a response handler for the root URL /. Inside the handler block, we set the X-Custom-Header header using the res[]= method and set the response body to "Hello, world!" using the res.body= method.

Finally, we start the server using the start method. Now you can visit http://localhost:8000/ in your web browser and see the "Hello, world!" response with the custom header.

gistlibby LogSnag