Created
February 19, 2015 12:10
-
-
Save cpedrinaci/bdcac7d25685909eb966 to your computer and use it in GitHub Desktop.
Simple script for launching an HTTP Server with CORS enabled. Includes index.json as part of the default index files to serve
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /usr/bin/env python2 | |
from SimpleHTTPServer import SimpleHTTPRequestHandler | |
import os | |
import BaseHTTPServer | |
class CORSRequestHandler (SimpleHTTPRequestHandler): | |
def end_headers (self): | |
self.send_header('Access-Control-Allow-Origin', '*') | |
SimpleHTTPRequestHandler.end_headers(self) | |
def send_head (self): | |
"""Common code for GET and HEAD commands. | |
This sends the response code and MIME headers. | |
Return value is either a file object (which has to be copied | |
to the outputfile by the caller unless the command was HEAD, | |
and must be closed by the caller under all circumstances), or | |
None, in which case the caller has nothing further to do. | |
""" | |
path = self.translate_path(self.path) | |
f = None | |
if os.path.isdir(path): | |
for index in "index.html", "index.htm", "index.json": | |
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) | |
if ctype.startswith('text/'): | |
mode = 'r' | |
else: | |
mode = 'rb' | |
try: | |
f = open(path, mode) | |
except IOError: | |
self.send_error(404, "File not found") | |
return None | |
self.send_response(200) | |
self.send_header("Content-type", ctype) | |
self.end_headers() | |
return f | |
def guess_type(self, path): | |
mimetype = SimpleHTTPRequestHandler.guess_type(self, path) | |
if mimetype == 'application/octet-stream': | |
if path.endswith('json'): | |
mimetype = 'application/json' | |
return mimetype | |
if __name__ == '__main__': | |
BaseHTTPServer.test(CORSRequestHandler, BaseHTTPServer.HTTPServer) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment