Skip to content

Instantly share code, notes, and snippets.

@dkavanagh
Last active December 18, 2015 09:18
Show Gist options
  • Save dkavanagh/5759928 to your computer and use it in GitHub Desktop.
Save dkavanagh/5759928 to your computer and use it in GitHub Desktop.
http redirector that works with tornado. start_redirector (in my code) gets called in a background thread.. ignore the callback arg, which is None, but kwargs is passed in containing use_ssl and port as values for the redirect handler.
def start_redirector(kwargs, callback):
# can't use tornado for this (not threadsafe). Must use something else, something simpler!
http_port = 8888
if eucaconsole.config.has_option('server', 'http.port'):
http_port = eucaconsole.config.getint('server', 'http.port')
server = BaseHTTPServer.HTTPServer(('localhost', http_port),
lambda *args: RedirectHandler(kwargs, *args))
server.serve_forever()
class RedirectHandler(BaseHTTPRequestHandler):
def __init__(self, kwargs, *args):
self._url = 'https' if kwargs['use_ssl'] else 'http'
self._url += '://%s:'+str(kwargs['port'])+'/'
BaseHTTPServer.BaseHTTPRequestHandler.__init__(self, *args)
def do_GET(self):
self.send_response(301)
host = self.headers.dict['host']
if host.find(':') > -1:
host = host.split(':')[0]
self.send_header("Location", self._url % host)
self.end_headers()
logging.info("Redirected http request")
return
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment