create a http server on a specific port in ruby

main.rb
require 'socket'

server = TCPServer.new('localhost', 8080)

loop do
  client = server.accept

  request = client.gets
  puts request

  response = "Hello World!\n"
  headers = {
    "Content-Type" => "text/plain",
    "Content-Length" => response.length,
    "Connection" => "close"
  }
  header_string = headers.map { |k, v| "#{k}: #{v}\r\n" }.join

  client.print "HTTP/1.1 200 OK\r\n#{header_string}\r\n#{response}"
  client.close
end
439 chars
22 lines

The above code creates a HTTP server on port 8080. When a client makes a request to this server, it responds with a "Hello World!" message. You can change the response to whatever you want. Note that this is a very basic example and should not be used in production, as it does not handle errors or other requests besides the initial GET request.

related categories

gistlibby LogSnag