Created
March 5, 2020 11:53
-
-
Save tachyons/e527f1952216024914d45837e3bbc048 to your computer and use it in GitHub Desktop.
Simple http server in ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# frozen_string_literal: true | |
require 'socket' | |
require 'time' | |
server = TCPServer.new 2000 # Server bound to port 2000 | |
def parse(request_string) | |
method, path, version = request_string.lines[0].split | |
{ | |
method: method, | |
path: path, | |
headers: parse_headers(request_string) | |
} | |
end | |
def parse_headers(request) | |
headers = {} | |
request.lines[1..-1].each do |line| | |
return headers if line == "\r\n" | |
header, value = line.split | |
header = normalize(header) | |
headers[header] = value | |
end | |
end | |
def normalize(header) | |
header.gsub(':', ' ').downcase.to_sym | |
end | |
def format_response(body) | |
<<~HTML | |
HTTP/1.1 200 OK | |
Date: #{Time.now.rfc2822} | |
Server: My custom script | |
Last-Modified: #{Time.now.rfc2822} | |
Content-Length: #{body.length + 200} | |
Content-Type: text/html | |
Connection: Closed | |
<html> | |
<body> | |
<p>#{body} </p> | |
</body> | |
</html> | |
HTML | |
end | |
loop do | |
client = server.accept # Wait for a client to connect | |
request = client.readpartial(2048) | |
puts parse(request) | |
client.puts format_response("Your request body is #{request}") | |
client.close | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment