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

To create an HTTP server in Ruby, we can use the built-in WEBrick library. Here is an example of creating a HTTP server and parsing the POST request body as form data:

main.rb
require 'webrick'
require 'uri'

# create a server
server = WEBrick::HTTPServer.new(Port: 8000)

# handle POST request
server.mount_proc '/' do |req, res|
  if req.request_method == 'POST'
    # read the request body
    body = URI.decode_www_form(req.body)

    # print the form data
    p body

    # set the response
    res.body = 'Form data received.'
  else
    # set the response for other request methods
    res.body = 'Hello, World!'
  end
end

# start the server
server.start
487 chars
26 lines

In this example, we create a HTTP server and mount a block to handle the requests. Inside the block, we first check if the request method is POST. If it is, we parse the request body as form data using the URI.decode_www_form method. Then we print the form data and set the response body to confirm that the form data was received.

To start the server, we simply call server.start. The server will listen on port 8000 by default.

gistlibby LogSnag