-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.rb
executable file
·77 lines (67 loc) · 1.65 KB
/
server.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#!/usr/bin/env ruby
require 'socket'
def main
socket = Socket.new(:INET, :STREAM)
socket.setsockopt(Socket::SOL_SOCKET, Socket::SO_REUSEADDR, true)
socket.bind(Addrinfo.tcp("127.0.0.1", 9000))
socket.listen(0)
conn_sock, addr_info = socket.accept
conn = Connection.new(conn_sock)
request = read_request(conn)
respond_for_request(conn_sock, request)
end
class Connection
def initialize(conn_sock)
@conn_sock = conn_sock
@buffer = ""
end
def read_line
read_until("\r\n")
end
def read_until(string)
until @buffer.include?(string)
@buffer += @conn_sock.recv(7)
end
result, @buffer = @buffer.split(string, 2)
result
end
end
def read_request(conn)
request_line = conn.read_line
method, path, version = request_line.split(" ", 3)
headers = {}
loop do
line = conn.read_line
break if line.empty?
key, value = line.split(/:\s*/, 2)
headers[key] = value
end
Request.new(method, path, headers)
end
Request = Struct.new(:method, :path, :headers)
def respond_for_request(conn_sock, request)
path = Dir.getwd + request.path
if File.exists?(path)
if File.executable?(path)
content = `#{path}`
else
content = File.read(path)
end
status_code = 200
else
content = ""
status_code = 404
end
respond(conn_sock, status_code, content)
end
def respond(conn_sock, status_code, content)
status_text = {
200 => "OK",
404 => "Not Found",
}.fetch(status_code)
conn_sock.send("HTTP/1.1 #{status_code} #{status_text}\r\n",0)
conn_sock.send("Content-Length: #{content.length}\r\n",0)
conn_sock.send("\r\n",0)
conn_sock.send(content,0)
end
main