-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtiny-core.py
60 lines (49 loc) · 1.43 KB
/
tiny-core.py
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
import socket
import request, response, router
HOST, PORT = '', 8889
static_root = './www'
def sendStaticContent(uri, res):
ext = uri.split('.')[-1]
print ext
if ext == 'html':
res.sendHtml(uri)
elif ext == 'png':
res.sendPng(uri)
elif ext == 'css':
res.sendCss(uri)
else:
raise Exception('Unsupported file format')
return
sock_conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock_conn.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock_conn.bind((HOST, PORT))
sock_conn.listen(3)
routes = router.Router()
print "Tiny is listening on", PORT
routes.add('/', lambda res: res.sendHtml('./www/index.html'))
routes.add('/index2', lambda res: res.sendHtml('./www/index2.html'))
routes.add('/tiny', lambda res: res.sendPng('./www/img/cat.png'))
routes.add('/tiny-css', lambda res: res.sendCss('./www/css/style.css'))
while True:
conn, addr = sock_conn.accept()
print "Connection from", addr
data = conn.recv(1024)
res = response.Response(conn);
try:
req = request.Request(data)
res_worker = routes.get(req.headers['uri'])
res_worker(res)
conn.close()
except KeyError:
#try serving static content
print "Falling back to static content..."
req = request.Request(data)
req_uri = static_root + req.headers['uri']
sendStaticContent(req_uri, res)
conn.close()
except Exception:
#send 404 when the route is not defined
print "Resource not found..."
res.sendNotFound()
conn.close()
sock_conn.close()