Skip to content

Instantly share code, notes, and snippets.

@lucianghinda
Last active April 30, 2023 08:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lucianghinda/11f66e3b9a25cac1835c58f673a58304 to your computer and use it in GitHub Desktop.
Save lucianghinda/11f66e3b9a25cac1835c58f673a58304 to your computer and use it in GitHub Desktop.
Sample HTTP server in Ruby
require 'socket'
class Handler
def initialize(port)
@server = TCPServer.new(port)
end
def start
loop do
client = @server.accept
handle_client(client)
end
end
def handle_client(client)
request = read_request(client)
response = process_request(request)
client.puts response
client.close
end
def read_request(client)
request = ''
while (line = client.gets) && !line.chomp.empty?
request += line
end
request
end
def process_request(request)
method, path, version = request.lines[0].split
if method == "GET" && path == "/hello"
"HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\n\r\nHello World!\n"
else
"HTTP/1.1 404 Not Found\r\nContent-Type: text/plain\r\n\r\n404 Not Found\n"
end
end
end
server = Handler.new(3000)
puts "Running on http://localhost:3000"
server.start
# This is code from https://www.reddit.com/r/ruby/comments/12zsvqe/comment/jhu9y9g/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment