-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttpserver.rb
48 lines (41 loc) · 919 Bytes
/
httpserver.rb
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
require "socket"
server = TCPServer.new(2000)
def read_request(client)
lines = []
while raw_input = client.gets
line = raw_input.chomp if raw_input
lines << line
p line
if line.empty?
x = lines.first.split(" ")
path = x[1].split("?")[0]
return {
verb: x[0],
path: path,
protocol: x[2]
}
end
end
end
def handle_request(request, &block)
response = { body: "", status: "404 Not Found" }
if request[:path] == "/test"
response[:status] = "200 OK"
response[:body] = "hooray!"
end
yield response
end
loop do
client = server.accept
request = read_request(client)
p request
handle_request(request) do |response|
client.puts "HTTP/1.1 #{response[:status]}"
client.puts "Content-Type: text/html"
client.puts ""
response[:body].split("\n").each do |line|
client.puts line
end
end
client.close
end