#!/usr/bin/env python3
# Reflects the requests from HTTP methods GET, POST, PUT, and DELETE
# Originaly written by Nathan Hamiel (2010)

from http.server import HTTPServer, BaseHTTPRequestHandler
from optparse import OptionParser
import argparse

class RequestHandler(BaseHTTPRequestHandler):

    def do_GET(self):
        request_path = self.path
        print("\n----- Request Start ----->\n")
        print(request_path)
        print(self.headers)
        print("<----- Request End -----\n")
        self.send_response(200)
        self.send_header("Set-Cookie", "foo=bar")

    def do_POST(self):
        request_path = self.path
        print("\n----- Request Start ----->\n")
        print(request_path)
        request_headers = self.headers
        content_length = request_headers.get('content-length')
        length = int(content_length[0]) if content_length else 0
        print(request_headers)
        print(self.rfile.read(length))
        print("<----- Request End -----\n")
        self.send_response(200)
    do_PUT = do_POST
    do_DELETE = do_GET

def main(port):
    print('Listening on localhost:%s' % port)
    server = HTTPServer(('', port), RequestHandler)
    server.serve_forever()


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Creates an http-server that will echo out any GET or POST parameters")
    parser.add_argument('-p', '--port', required=False, type=int, default=8888, action='store',
                        dest='port', help="TCP port to listen (default 8888)")
    args = parser.parse_args()
    main(args.port)
