Tuesday, April 27, 2010

HTTP Redirection, Take 2

Further to the comment posted, here is a revised version for redirection driven by configuration file.

#! /usr/local/bin/python


import sys, os
import BaseHTTPServer


if len(sys.argv) != 2:
    sys.stderr.write("Usage: %s &lgt;config-file>\n" % sys.argv[0])
    sys.exit(1)



#
# config file:
# 1 line 2 fields (port, url)
#
config = sys.argv[1]
if not os.path.exists(config):
    sys.stderr.write("Error. Config file '%s' does not exist" % config)
    sys.exit(2)
else:
    fp = open(config, 'r')
    (port, url) = fp.readline().rstrip().split()



class RedirectHandler(BaseHTTPServer.BaseHTTPRequestHandler):
    # just redirect regardless of uri
    def do_GET(s):
        s.send_response(302)
        s.send_header('Location', url)
        s.end_headers()

    # ignore output
    def log_message(s, format, *args):
        pass



if __name__ == '__main__':
    server_class = BaseHTTPServer.HTTPServer
    httpd = server_class( ('', int(port)), RedirectHandler)
    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        pass
    httpd.server_close()

Sample content of a typical file to listen at port 1668 to www.google.com:

1668 http://www.google.com/

Tested on my Cygwin

Labels:

0 Comments:

Post a Comment

<< Home