create a http server with a head route in ruby

Here's an example code snippet to create a HTTP server with a HEAD route in Ruby:

main.rb
require 'webrick'

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

server.mount_proc '/test' do |req, res|
  if req.head?
    # Set headers to return on the response
    res['Content-Type'] = 'text/plain'
    res['Custom-Header'] = 'Hello, world!'

    # Set response status code to successful HEAD request
    res.status = 200

    # Return an empty body
    res.body = ''
  else
    # Return a 400 Bad Request for requests other than HEAD
    res.status = 400
    res.body = 'Bad Request'
  end
end

trap('INT') { server.shutdown }

# Start the server
server.start
565 chars
27 lines

The code uses the built-in WEBrick library to create an HTTP server listening on port 8000. The server then maps a block of code to the /test route using mount_proc.

Inside the block, the req.head? method is used to determine if the incoming request is a HEAD request. If so, the appropriate headers are set on the response, the status code is set to 200, and an empty response body is returned.

If the incoming request is not a HEAD request, a 400 Bad Request status code is returned with an error message in the response body.

The server is then started and will listen for incoming requests until it is shut down.

gistlibby LogSnag