Skip to content

Instantly share code, notes, and snippets.

@aagallag
Forked from huyng/reflect.py
Last active July 12, 2016 05:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aagallag/89682f7ff03385c07780d94dd798b7cd to your computer and use it in GitHub Desktop.
Save aagallag/89682f7ff03385c07780d94dd798b7cd to your computer and use it in GitHub Desktop.
A simple echo server to inspect http web requests
#!/usr/bin/env python
# Reflects the requests from HTTP methods GET, POST, PUT, and DELETE
# Written by Nathan Hamiel (2010)
# Modifications by Aaron Gallagher (2016)
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
from optparse import OptionParser
import datetime
LOG_FILE = 'log_%s.txt' % datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S')
class RequestHandler(BaseHTTPRequestHandler):
logfile = open(LOG_FILE, 'w')
def do_GET(self):
request_path = self.path
self.log("\n----- Request Start ----->\n")
self.log(request_path)
self.log(self.headers)
self.log("<----- Request End -----\n")
self.send_response(200)
self.send_header("Set-Cookie", "foo=bar")
def do_POST(self):
request_path = self.path
self.log("\n----- Request Start ----->\n")
self.log(request_path)
request_headers = self.headers
content_length = request_headers.getheaders('content-length')
length = int(content_length[0]) if content_length else 0
self.log(request_headers)
self.log(self.rfile.read(length))
self.log("<----- Request End -----\n")
self.send_response(200)
do_PUT = do_POST
do_DELETE = do_GET
def log(self, msg):
print(msg)
self.logfile.write(str(msg))
def main():
port = 8080
print('Listening on localhost:%s' % port)
server = HTTPServer(('', port), RequestHandler)
server.serve_forever()
if __name__ == "__main__":
parser = OptionParser()
parser.usage = ("Creates an http-server that will echo out any GET or POST parameters\n"
"Run:\n\n"
" reflect")
(options, args) = parser.parse_args()
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment