-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttpserver.py
More file actions
executable file
·75 lines (64 loc) · 2.25 KB
/
httpserver.py
File metadata and controls
executable file
·75 lines (64 loc) · 2.25 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#!/usr/bin/env python3
import sys, os, socket, datetime, mimetypes
CHUNKSIZE = 8192
def getline(file):
return file.readline().decode().rstrip('\r\n')
def handle_get_head(rfile, wfile, path, headers, head=False):
path = path.lstrip('/')
try:
file = open(path, 'rb')
except OSError as e:
print(e)
wfile.write(b'HTTP/1.1 404 Not Found\r\n\r\n')
else:
with file:
stat = os.stat(file.fileno())
wfile.write(b'HTTP/1.1 200 OK\r\n')
respheaders = {
'Date': datetime.datetime.utcnow().ctime(),
'Server': 'httpserver.py',
'Content-Length': stat.st_size,
'Content-Type':
mimetypes.guess_type(path)[0] or 'application/octet-stream',
'Last-Modified':
datetime.datetime.utcfromtimestamp(stat.st_mtime).ctime(),
'Connection': 'close',
}
for k, v in respheaders.items():
wfile.write('{}: {}\r\n'.format(k, v).encode())
wfile.write(b'\r\n')
if not head:
chunk = file.read(CHUNKSIZE)
while chunk:
wfile.write(chunk)
chunk = file.read(CHUNKSIZE)
def handle(conn):
rfile = conn.makefile('rb')
wfile = conn.makefile('wb')
req = getline(rfile)
print('{}:{}: {}'.format(*conn.getpeername(), req))
method, path, version = req.split()
headers = {}
line = getline(rfile)
while line:
key, value = line.split(':', 1)
headers[key.strip().title()] = value.strip()
line = getline(rfile)
if method == 'GET':
handle_get_head(rfile, wfile, path, headers)
elif method == 'HEAD':
handle_get_head(rfile, wfile, path, headers, True)
else:
wfile.write(b'HTTP/1.1 501 Method Not Implemented\r\n\r\n')
def serve(port=80):
with socket.socket() as sock:
sock.bind(('', port))
sock.listen()
print('Listening on {}:{}...'.format(*sock.getsockname()))
while True:
conn, addr = sock.accept()
with conn:
handle(conn)
if __name__ == '__main__':
port = int(sys.argv[1]) if len(sys.argv) > 1 else 80
serve(port)