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

Here's an example code snippet that creates an HTTP server in Ruby and reads the request body as HTML:

main.rb
require 'socket'

server = TCPServer.new 3000

loop do
  client = server.accept

  # read the request (including headers)
  request = client.recv(1024)

  # extract the request body
  body_start = request.index("\r\n\r\n") + 4
  body = request[body_start..-1]

  # assume that the body is HTML and print it
  puts "Request body: #{body}"

  # send a response back to the client
  response = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<html><body>Hello, world!</body></html>"
  client.puts response

  client.close
end
526 chars
24 lines

This code listens for incoming connections on port 3000, accepts the connection and reads the request headers and body. It then prints the request body (assuming that it's HTML). Finally, it sends a basic "Hello, world!" HTML response back to the client.

Note that this is a very basic example, and doesn't handle errors or multiple requests at the same time.

gistlibby LogSnag