Skip to content

Instantly share code, notes, and snippets.

@filipecifali
Created July 13, 2018 12:26
Show Gist options
  • Save filipecifali/6b0aff45b04293ab9640c2e28f06982f to your computer and use it in GitHub Desktop.
Save filipecifali/6b0aff45b04293ab9640c2e28f06982f to your computer and use it in GitHub Desktop.
To support pretty URL rewriting and using python(2|3)
### Usage: python custom_server.py $PORT $DIR
# i.e.: python custom_server 8000 public/new
import platform
if platform.python_version()[0] == '3':
from http.server import SimpleHTTPRequestHandler as SHRH
from socketserver import TCPServer
elif platform.python_version()[0] == '2':
from SimpleHTTPServer import SimpleHTTPRequestHandler as SHRH
from SocketServer import TCPServer
from sys import argv
import re
import os
class Server(SHRH):
def do_GET(self):
# mathc anything that doesn't have extensions
# and ignores if it's a existing directory
matches = re.match('(.*)\.(.*)', self.path)
## FIXME: os.path.join resets the whole join if it's an absolute path
# turns out URI starts with an absolute path symbol
# so we join everything after first char
if not matches and not os.path.isdir(os.path.join(os.path.dirname(os.path.abspath(__file__)), self.path[1:])) and not self.path == '/':
self.path = '.'.join([self.path, 'html'])
"""Serve a GET request."""
f = self.send_head()
if f:
try:
self.copyfile(f, self.wfile)
finally:
f.close()
@classmethod
def serve_forever(self, port):
os.chdir(argv[2])
TCPServer(('', port), Server).serve_forever(port)
if __name__ == "__main__":
Server.serve_forever(int(argv[1]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment