-
-
Save jiacai2050/cedd4c17954acca27559bfee874ce14b to your computer and use it in GitHub Desktop.
Python HTTP server that echos GET requests
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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