Skip to content

Instantly share code, notes, and snippets.

@mgoodness
Created November 10, 2015 17:19
Show Gist options
  • Save mgoodness/f73d3529b37ab7030c26 to your computer and use it in GitHub Desktop.
Save mgoodness/f73d3529b37ab7030c26 to your computer and use it in GitHub Desktop.
Python HTTP server that echos GET requests
#!/usr/bin/env python
# Reflects the requests from HTTP GET methods
# Written by Nathan Hamiel (2010), modified by Michael Goodness (2015)
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
from argparse import ArgumentParser
from urlparse import urlparse
import daemon
import socket
class RequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
parsed_path = urlparse(self.path)
message_parts = [
'hostname=%s' % socket.gethostname(),
'path=%s' % self.path,
'real path=%s' % parsed_path.path,
'HEADERS:',
]
for name, value in sorted(self.headers.items()):
message_parts.append('%s=%s' % (name, value.rstrip()))
message_parts.append('')
message = '\r\n'.join(message_parts)
self.send_response(200)
self.end_headers()
self.wfile.write(message)
return
do_DELETE = do_GET
def main():
parser = ArgumentParser(
description='An http server that echos GET requests')
parser.add_argument(
'--port', default=8080, help='listening port [default: 8080]')
args = parser.parse_args()
server = HTTPServer(('', int(args.port)), RequestHandler)
daemon_context = daemon.DaemonContext()
daemon_context.files_preserve = [server.fileno()]
with daemon_context:
server.serve_forever()
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment