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

Here's an example of how to create an HTTP server using Rack and read the request body as multipart form data in Ruby:

main.rb
require 'rack'

class MyApp
  def call(env)
    request = Rack::Request.new(env)
    if request.post? && request.content_type =~ /multipart\/form-data/
      # Read the request body as multipart form data
      form_data = request.params["form_data"]
      # Do something with the form data
      puts form_data.inspect
    end

    # Return a response
    [200, {"Content-Type" => "text/plain"}, ["Hello, world!"]]
  end
end

Rack::Handler::WEBrick.run MyApp.new, :Port => 8080
479 chars
19 lines

In this example, we create a new Rack::Request object from the env argument passed to the call method. We then check if the request is a POST request and has a content type of multipart/form-data. If it does, we can read the request body as a hash of values using the request.params method, where the key is the name of the form field and the value is the value of the field.

You can run this server with the following command:

main.rb
$ ruby app.rb
14 chars
2 lines

And you can test it with a curl command like this:

main.rb
$ curl -X POST -F "form_data[username]=testuser" -F "form_data[password]=testpass" http://localhost:8080
105 chars
2 lines

gistlibby LogSnag