create a http server and read the request body in ruby

To create a simple HTTP server in Ruby, we can use the WEBrick module which is included in the Ruby standard library. Here's an example:

main.rb
require 'webrick'

class MyServer < WEBrick::HTTPServlet::AbstractServlet
  def do_POST(request, response)
    body = request.body
    # Do something with the request body
    response.status = 200
    response.body = "Received POST request with body: #{body}"
  end
end

server = WEBrick::HTTPServer.new(Port: 8000)
server.mount "/", MyServer
trap("INT") { server.shutdown }
server.start
389 chars
16 lines

In this example, we define a MyServer class that inherits from WEBrick::HTTPServlet::AbstractServlet and implements the do_POST method. This method is called whenever the server receives a POST request.

Inside the do_POST method, we can access the request body through the request.body property. We can then do whatever we want with the request body, and set the response accordingly. In this case, we're just setting the response body to include the request body that we received.

We then create a new instance of WEBrick::HTTPServer and mount our MyServer class to the root URL path ("/"). Finally, we start the server and trap the INT signal to gracefully shut down the server when we need to.

Note that this is just a simple example and there are many other things you can do with the WEBrick module to customize your HTTP server.

related categories

gistlibby LogSnag