Created
March 4, 2024 13:57
-
-
Save oyvinev/a13e54d498a3a711f22a3888edef1aea to your computer and use it in GitHub Desktop.
Simple redirect with message and countdown delay
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Run like