create a http server with a put route in ruby

To create a simple HTTP server with a PUT route in Ruby, we can use the WEBrick module that comes bundled with Ruby.

main.rb
require 'webrick'
require 'json'

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

server.mount_proc '/data' do |req, res|
  case req.request_method
  when 'PUT'
    data = JSON.parse(req.body)
    # do something with the data
    res.body = 'Data received successfully!'
    res.status = 200
  else
    res.status = 405
    res.body = 'HTTP Method not allowed'
  end
end

trap 'INT' do
  server.shutdown
end

server.start
420 chars
24 lines

In the above code, we start by requiring the necessary modules WEBrick and JSON. We then create a new WEBrick::HTTPServer instance on port 8000. Next, we mount a Proc handler on the /data route.

The handler checks if the HTTP method is PUT. If it is, we parse the JSON payload using the JSON.parse method and do something with the data. In this example, we simply return a success message. If the method is not PUT, we return a 405 Method Not Allowed response.

Finally, we set up a signal trap to listen for CTRL-C SIGINT signals, which allows us to gracefully shutdown the server when it is interrupted. We then start the server by calling the start method on the server instance.

gistlibby LogSnag