-
Notifications
You must be signed in to change notification settings - Fork 0
/
serve
executable file
·57 lines (53 loc) · 2.08 KB
/
serve
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
#!/usr/bin/env python
try:
from SimpleHTTPServer import SimpleHTTPRequestHandler
import BaseHTTPServer
HTTPServer = BaseHTTPServer.HTTPServer
except ImportError:
# PY3
from http.server import (SimpleHTTPRequestHandler, BaseHTTPRequestHandler, HTTPServer)
import http.server as BaseHTTPServer
import os
# essentially like SimpleHTTPRequestHandler, but sets the allow origin
# header.
class RelaxedRequestHandler(SimpleHTTPRequestHandler):
def send_head(self):
"""
This is a verbatim copy of the SimpleHTTPRequestHandler.send_head
method. There are no other ways to inject the Allow-Origin
header here...
"""
path = self.translate_path(self.path)
f = None
if os.path.isdir(path):
if not self.path.endswith('/'):
# redirect browser - doing basically what apache does
self.send_response(301)
self.send_header("Location", self.path + "/")
self.end_headers()
return None
for index in "index.html", "index.htm":
index = os.path.join(path, index)
if os.path.exists(index):
path = index
break
else:
return self.list_directory(path)
ctype = self.guess_type(path)
try:
# Always read in binary mode. Opening files in text mode may cause
# newline translations, making the actual size of the content
# transmitted *less* than the content-length!
f = open(path, 'rb')
except IOError:
self.send_error(404, "File not found")
return None
self.send_response(200)
self.send_header("Content-type", ctype)
fs = os.fstat(f.fileno())
self.send_header("Content-Length", str(fs[6]))
self.send_header('Access-Control-Allow-Origin', '"*"')
self.send_header("Last-Modified", self.date_time_string(fs.st_mtime))
self.end_headers()
return f
BaseHTTPServer.test(RelaxedRequestHandler, HTTPServer)