Skip to content

Instantly share code, notes, and snippets.

@oyvinev
Created March 4, 2024 13:57
Show Gist options
  • Save oyvinev/a13e54d498a3a711f22a3888edef1aea to your computer and use it in GitHub Desktop.
Save oyvinev/a13e54d498a3a711f22a3888edef1aea to your computer and use it in GitHub Desktop.
Simple redirect with message and countdown delay
#!/usr/bin/env python
from http import server as SimpleHTTPServer
import argparse
TEMPLATE = """
<html>
<head>
<title>Page moved</title>
</head>
<body style="display: flex; margin: 10rem; flex-direction: column; align-items: center;font-weight: bolder;">
<p>{message}</p>
<p>You will be redirected to {url} in <span id="timer"></span> seconds</p>
</body>
<script>
var v = 10
document.getElementById('timer').innerText = v;
const timer = setInterval(() => {{
v--;
document.getElementById('timer').innerText = v;
if (v < 0) {{
clearInterval(timer);
window.location='{url}'
}}
}}, 1000);
</script>
</html>
"""
def redirect_handler_factory(url, message=""):
"""
Returns a request handler class that redirects to supplied `url`
"""
class RedirectHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
self.wfile.write(TEMPLATE.format(url=url.rstrip("/")+self.path, message=message).encode("utf-8"))
return RedirectHandler
def main():
parser = argparse.ArgumentParser(description='HTTP redirect server')
parser.add_argument('--port', '-p', action="store", type=int, default=80, help='port to listen on')
parser.add_argument('--ip', '-i', action="store", default="", help='host interface to listen on')
parser.add_argument('--message', action="store", default="", help='message to display on redirect page')
parser.add_argument('redirect_url', action="store")
args = parser.parse_args()
redirectHandler = redirect_handler_factory(args.redirect_url, args.message)
handler = SimpleHTTPServer.HTTPServer((args.ip, args.port), redirectHandler)
print(f"serving at port {args.port}")
handler.serve_forever()
if __name__ == "__main__":
main()
@oyvinev
Copy link
Author

oyvinev commented Mar 4, 2024

Run like

python redirect.py -p 8080 --message "Service has been moved to <i>http://new-url:8080</i>. Please update all bookmarks." http://new-url:8080

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment