Dimitrios Mavrommatis | 2fd4ecd | 2017-12-18 14:44:38 -0800 | [diff] [blame] | 1 | #!/usr/bin/env python |
| 2 | # Reflects the requests from HTTP methods GET, POST, PUT, and DELETE |
| 3 | # Written by Nathan Hamiel (2010) |
| 4 | |
| 5 | from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler |
| 6 | from optparse import OptionParser |
| 7 | |
| 8 | class RequestHandler(BaseHTTPRequestHandler): |
| 9 | |
| 10 | def do_GET(self): |
| 11 | |
| 12 | request_path = self.path |
| 13 | |
| 14 | print("\n----- Request Start ----->\n") |
| 15 | print(request_path) |
| 16 | print(self.headers) |
| 17 | print("<----- Request End -----\n") |
| 18 | |
| 19 | self.send_response(200) |
| 20 | self.send_header("Set-Cookie", "foo=bar") |
| 21 | |
| 22 | def do_POST(self): |
| 23 | |
| 24 | request_path = self.path |
| 25 | |
| 26 | print("\n----- Request Start ----->\n") |
| 27 | print(request_path) |
| 28 | |
| 29 | request_headers = self.headers |
| 30 | content_length = request_headers.getheaders('content-length') |
| 31 | length = int(content_length[0]) if content_length else 0 |
| 32 | |
| 33 | print(request_headers) |
| 34 | print(self.rfile.read(length)) |
| 35 | print("<----- Request End -----\n") |
| 36 | |
| 37 | self.send_response(200) |
| 38 | |
| 39 | do_PUT = do_POST |
| 40 | do_DELETE = do_GET |
| 41 | |
| 42 | def main(): |
slowr | d77bf91 | 2018-01-13 06:38:15 -0500 | [diff] [blame] | 43 | port = 8181 |
Dimitrios Mavrommatis | 2fd4ecd | 2017-12-18 14:44:38 -0800 | [diff] [blame] | 44 | print('Listening on localhost:%s' % port) |
| 45 | server = HTTPServer(('', port), RequestHandler) |
| 46 | server.serve_forever() |
| 47 | |
| 48 | |
| 49 | if __name__ == "__main__": |
| 50 | parser = OptionParser() |
| 51 | parser.usage = ("Creates an http-server that will echo out any GET or POST parameters\n" |
| 52 | "Run:\n\n" |
| 53 | " reflect") |
| 54 | (options, args) = parser.parse_args() |
| 55 | |
slowr | d77bf91 | 2018-01-13 06:38:15 -0500 | [diff] [blame] | 56 | main() |