-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathtiny_web_server.rb
More file actions
52 lines (47 loc) · 1.38 KB
/
tiny_web_server.rb
File metadata and controls
52 lines (47 loc) · 1.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
require 'socket'
require 'logger'
require './surfing_app'
class TinyWebServer
def initialize(host, port)
@host = host
@port = port
@logger = Logger.new(STDOUT)
end
def run(app)
server = TCPServer.open(@host, @port)
@logger.info("HTTP Server ready to accept requests!")
loop do
connection = server.accept
@logger.info "Opening a connection for request:"
message_line = connection.gets
@logger.info message_line
env = parse_http_header(message_line)
begin
message_line = connection.gets
end until message_line.chomp == ""
response = app.call(env)
@logger.info "Sending response..."
connection.puts "HTTP/1.1 #{response[0]} #{response_status(response[0])}"
connection.puts "Date: #{Time.now.ctime}"
connection.puts "Content-Type: #{response[1]['Content-Type']}"
connection.puts "Server: Tiny Web Server"
connection.puts
connection.puts response[2][0]
connection.close
@logger.info "Response sent and connection closed."
end
end
def parse_http_header(header_string)
method, path, protocol = header_string.split(' ')
{method: method, path: path, protocol: protocol}
end
def response_status(response_code)
case response_code
when 200
"OK"
when 404
"NOT FOUND"
end
end
end
TinyWebServer.new('localhost', 2000).run(Surfing.new)