http-redirect.py
2.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#!/usr/bin/env python3
# python standard library
from os import path
import sys
import argparse
import signal
# user installed libraries
from tornado import ioloop, web, httpserver
# ============================================================================
# WebApplication - Tornado Web Server
# ============================================================================
class WebRedirectApplication(web.Application):
def __init__(self, target='https://localhost'):
handlers = [
(r'/*', RootHandler), # redirect to https
]
super().__init__(handlers)
self.target = target
# ============================================================================
# Handlers
# ============================================================================
class RootHandler(web.RequestHandler):
SUPPORTED_METHODS = ['GET']
def get(self):
print('Redirecting...')
self.redirect(self.application.target)
# -------------------------------------------------------------------------
def signal_handler(signal, frame):
r = input(' --> Stop webserver? (yes/no) ').lower()
if r == 'yes':
ioloop.IOLoop.current().stop()
print('Webserver stopped.')
sys.exit(0)
# -------------------------------------------------------------------------
# Tornado web server
# ----------------------------------------------------------------------------
def main():
# --- Commandline argument parsing
argparser = argparse.ArgumentParser(
description='Redirection server. Any request to http will be redirected to a target server provided in the command line argument.')
argparser.add_argument('target', type=str,
help='Target https server address, e.g. https://www.example.com.')
argparser.add_argument('--port', type=int, default=8080,
help='Port to which this server will listen to, e.g. 8080')
arg = argparser.parse_args()
# --- create web redirect application
try:
redirectapp = WebRedirectApplication(target=arg.target)
except Exception as e:
print('Failed to start web redirect application.')
raise e
# --- create webserver
try:
http_server = httpserver.HTTPServer(redirectapp)
except Exception as e:
print('Failed to create HTTP server.')
raise e
else:
http_server.listen(8080)
# --- run webserver
print(f'Redirecting port {arg.port} to {arg.target} (Ctrl-C to stop)')
signal.signal(signal.SIGINT, signal_handler)
try:
ioloop.IOLoop.current().start() # running...
except Exception as e:
print('Redirection stopped!')
ioloop.IOLoop.current().stop()
raise e
# ----------------------------------------------------------------------------
if __name__ == "__main__":
main()