Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to capture POST data from a simple Ruby server

Tags:

ruby

http-post

I have a basic Ruby server that I'd like to listen to a specific port, read incoming POST data and do blah...

I have this:

require 'socket'               # Get sockets from stdlib

server = TCPServer.open(2000)  # Socket to listen on port 2000
loop {                         # Servers run forever
  client = server.accept       # Wait for a client to connect
  client.puts(Time.now.ctime)  # Send the time to the client
  client.puts "Closing the connection. Bye!"
  client.close                 # Disconnect from the client
}

How would I go about capturing the POST data?

Thanks for any help.

like image 660
micahblu Avatar asked May 26 '14 19:05

micahblu


Video Answer


2 Answers

It's possible to do this without adding much to your server:

require 'socket'               # Get sockets from stdlib

server = TCPServer.open(2000)  # Socket to listen on port 2000
loop {                         # Servers run forever
  client = server.accept       # Wait for a client to connect
  method, path = client.gets.split                    # In this case, method = "POST" and path = "/"
  headers = {}
  while line = client.gets.split(' ', 2)              # Collect HTTP headers
    break if line[0] == ""                            # Blank line means no more headers
    headers[line[0].chop] = line[1].strip             # Hash headers by type
  end
  data = client.read(headers["Content-Length"].to_i)  # Read the POST data as specified in the header

  puts data                                           # Do what you want with the POST data

  client.puts(Time.now.ctime)  # Send the time to the client
  client.puts "Closing the connection. Bye!"
  client.close                 # Disconnect from the client
}
like image 124
quizzicus Avatar answered Oct 16 '22 08:10

quizzicus


For really simple apps you probably want to write something using Sinatra which is about as basic as you can get.

post('/') do 
  # Do stuff with post data stored in params
  puts params[:example]
end

Then you can stick this in a Rack script, config.ru, and host it easily using any Rack-compliant server.

like image 2
tadman Avatar answered Oct 16 '22 06:10

tadman