create a http server and read the request body as form url encoded in ruby

To create an HTTP server in Ruby, you can use the built-in WEBrick library. Here's an example that sets up a server and reads the request body as form-urlencoded:

main.rb
require 'webrick'
require 'uri'

class MyServer < WEBrick::HTTPServlet::AbstractServlet
  def do_POST(request, response)
    # Parse the form-urlencoded request body
    params = URI.decode_www_form(request.body)

    # Print the parameters to the console
    puts params.to_h.inspect

    # Set up the response headers and body
    response.status = 200
    response['Content-Type'] = 'text/plain'
    response.body = 'Received POST request'

    # Send the response
    server = WEBrick::HTTPServer.new(Port: 8000)
    server.mount '/', MyServer
    trap('INT') { server.shutdown }
    server.start
  end
end
611 chars
24 lines

In this example, we define a class MyServer that inherits from WEBrick::HTTPServlet::AbstractServlet. We then define a do_POST method that handles POST requests. Inside this method, we parse the form-urlencoded request body using URI.decode_www_form(request.body). This returns an array of key-value pairs, which we convert to a hash using to_h.

We then print the parameters to the console using puts, set up the response headers and body, and send the response using response.status = 200, response['Content-Type'] = 'text/plain', response.body = 'Received POST request', and response.send_response.

Finally, we set up the server to listen on port 8000 by creating a new WEBrick::HTTPServer object and calling server.mount('/', MyServer) to mount our MyServer class on the root URL. We also add a signal handler to shut down the server gracefully when we receive an interrupt signal, and start the server using server.start.

gistlibby LogSnag