Created
December 31, 2014 18:11
-
-
Save capeterson/1741f318e8ce6a47f9d7 to your computer and use it in GitHub Desktop.
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 python | |
import os, sys, re | |
from os import curdir, sep | |
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer | |
class MyHandler(BaseHTTPRequestHandler): | |
def do_GET(self): | |
try: | |
print "serving path: "+self.path | |
if self.path == "/": | |
print "serving index" | |
self.send_response(200) | |
self.send_header('Content-type', 'text/html') | |
self.send_header('Page', 'index') | |
self.end_headers() | |
self.wfile.write(getIndex()) | |
else: | |
match = re.match(r"/resource/[0-9]+/([^\?]*)", self.path) | |
if match: | |
localPath = os.path.normpath(match.group(1)) | |
print "Loading file at path "+localPath | |
f = open(curdir + sep + localPath) #Massivley insecure, only for local testing! | |
self.send_response(200) | |
self.send_header("Access-Control-Allow-Origin","*") | |
self.send_header("Access-Control-Allow-Headers","origin, x-requested-with, content-type") | |
self.send_header("Access-Control-Allow-Methods","PUT, GET, POST, DELETE, OPTIONS") | |
self.end_headers() | |
self.wfile.write(f.read()) | |
f.close() | |
else: | |
self.send_error(500,'Unable to parse resource URL: %s' % self.path) | |
return | |
except IOError: | |
self.send_error(404,'File Not Found: %s' % self.path) | |
def getIndex(): | |
print "Building index for "+curdir | |
folders = os.walk(curdir).next()[1] | |
print "folders found:", folders | |
content = "<html><head><title>Folder Listing</title></head><body><ul>" | |
for folder in folders: | |
content += "<li><a href='/"+folder+"''>"+folder+"</a></li>" | |
content += "</ul></body></html>" | |
return content | |
def main(): | |
try: | |
server = HTTPServer(('', 8080), MyHandler) | |
print 'started httpserver...' | |
server.serve_forever() | |
except KeyboardInterrupt: | |
print '^C received, shutting down server' | |
server.socket.close() | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment