create a http server and read the request body as text in ruby

To create a basic HTTP server that reads the request body as text in Ruby, you can use the built-in WEBrick module. Here's an example:

main.rb
require 'webrick'

# Create a new HTTP server listening on port 8000
server = WEBrick::HTTPServer.new(:Port => 8000)

# Define a custom handler that reads the request body as text and logs it
class RequestHandler < WEBrick::HTTPServlet::AbstractServlet
  def do_POST(request, response)
    # Set the response content type
    response.content_type = "text/plain"

    # Read the request body as text
    body = request.body.to_s

    # Log the request body to the console
    puts "Received request body:\n#{body}"

    # Send a response back to the client
    response.body = "Received request body:\n#{body}"
  end
end

# Mount the custom request handler to the server
server.mount("/", RequestHandler)

# Start the server
server.start
738 chars
28 lines

This code defines a custom RequestHandler class that logs the request body to the console and sends a response back to the client including the received body. The server listens on port 8000 and mounts the custom handler to the root path. When a POST request is made to the server, the handler is called and the request body is read as text. Finally, the server is started and will continue to run until terminated.

gistlibby LogSnag