2013-01-11 02:57:43 +01:00
|
|
|
from __future__ import print_function
|
2013-08-12 19:23:57 +01:00
|
|
|
import os
|
2013-03-16 19:29:10 +01:00
|
|
|
import sys
|
2013-08-12 19:23:57 +01:00
|
|
|
import logging
|
2013-01-11 02:57:43 +01:00
|
|
|
try:
|
|
|
|
|
import SimpleHTTPServer as srvmod
|
|
|
|
|
except ImportError:
|
2013-03-03 20:12:31 -08:00
|
|
|
import http.server as srvmod # NOQA
|
2013-01-11 02:57:43 +01:00
|
|
|
|
|
|
|
|
try:
|
|
|
|
|
import SocketServer as socketserver
|
|
|
|
|
except ImportError:
|
2013-03-03 20:12:31 -08:00
|
|
|
import socketserver # NOQA
|
2013-01-11 02:57:43 +01:00
|
|
|
|
2015-01-10 15:40:54 -08:00
|
|
|
PORT = len(sys.argv) in (2, 3) and int(sys.argv[1]) or 8000
|
|
|
|
|
SERVER = len(sys.argv) == 3 and sys.argv[2] or ""
|
2013-12-04 22:26:39 +11:00
|
|
|
SUFFIXES = ['', '.html', '/index.html']
|
|
|
|
|
|
2013-01-11 02:57:43 +01:00
|
|
|
|
2013-08-12 19:23:57 +01:00
|
|
|
class ComplexHTTPRequestHandler(srvmod.SimpleHTTPRequestHandler):
|
|
|
|
|
def do_GET(self):
|
2014-12-15 11:05:02 -08:00
|
|
|
# Try to detect file by applying various suffixes
|
2013-08-12 19:23:57 +01:00
|
|
|
for suffix in SUFFIXES:
|
2014-12-15 11:05:02 -08:00
|
|
|
if not hasattr(self, 'original_path'):
|
2013-08-12 19:23:57 +01:00
|
|
|
self.original_path = self.path
|
2014-12-15 11:05:02 -08:00
|
|
|
|
2013-08-12 19:23:57 +01:00
|
|
|
self.path = self.original_path + suffix
|
|
|
|
|
path = self.translate_path(self.path)
|
2014-12-15 11:05:02 -08:00
|
|
|
|
2013-08-12 19:23:57 +01:00
|
|
|
if os.path.exists(path):
|
2013-12-04 22:26:39 +11:00
|
|
|
srvmod.SimpleHTTPRequestHandler.do_GET(self)
|
2014-12-15 11:05:02 -08:00
|
|
|
logging.info("Found `%s`." % self.path)
|
2013-08-12 19:23:57 +01:00
|
|
|
break
|
2014-12-15 11:05:02 -08:00
|
|
|
|
|
|
|
|
logging.info("Tried to find `%s`, but it doesn't exist.",
|
|
|
|
|
self.path)
|
|
|
|
|
else:
|
|
|
|
|
# Fallback if there were no matches
|
|
|
|
|
logging.warning("Unable to find `%s` or variations.",
|
|
|
|
|
self.original_path)
|
2013-08-12 19:23:57 +01:00
|
|
|
|
|
|
|
|
Handler = ComplexHTTPRequestHandler
|
2013-01-11 02:57:43 +01:00
|
|
|
|
2014-02-13 15:46:33 -08:00
|
|
|
socketserver.TCPServer.allow_reuse_address = True
|
2013-03-16 19:29:10 +01:00
|
|
|
try:
|
2015-01-10 15:40:54 -08:00
|
|
|
httpd = socketserver.TCPServer((SERVER, PORT), Handler)
|
2013-03-16 19:29:10 +01:00
|
|
|
except OSError as e:
|
2014-12-15 11:05:02 -08:00
|
|
|
logging.error("Could not listen on port %s, server %s.", PORT, SERVER)
|
2013-03-16 19:29:10 +01:00
|
|
|
sys.exit(getattr(e, 'exitcode', 1))
|
|
|
|
|
|
2013-01-11 02:57:43 +01:00
|
|
|
|
2014-12-15 11:05:02 -08:00
|
|
|
logging.info("Serving at port %s, server %s.", PORT, SERVER)
|
2013-03-19 12:15:58 +01:00
|
|
|
try:
|
|
|
|
|
httpd.serve_forever()
|
|
|
|
|
except KeyboardInterrupt as e:
|
2014-12-15 11:05:02 -08:00
|
|
|
logging.info("Shutting down server.")
|
2013-12-04 22:26:39 +11:00
|
|
|
httpd.socket.close()
|