Last active
July 12, 2019 09:40
-
-
Save jnns/c82519fb4e4d7b599a5b75c0f848d1eb to your computer and use it in GitHub Desktop.
Echo incoming HTTP requests using the Python3 `http.server` module.
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 python3 | |
import argparse | |
from http.server import HTTPServer, BaseHTTPRequestHandler | |
class RequestHandler(BaseHTTPRequestHandler): | |
"""Print request headers/body and respond with empty JSON object.""" | |
def do_GET(self): | |
self.send_response(200) | |
print(self.headers) | |
self.end_headers() | |
self.wfile.write(b'{}') | |
def do_POST(self): | |
self.do_GET() | |
content_length = int(self.headers['content-length']) | |
if content_length: | |
print(self.rfile.read(content_length).decode()) | |
do_PUT = do_POST | |
do_PATCH = do_POST | |
do_DELETE = do_GET | |
if __name__ == "__main__": | |
parser = argparse.ArgumentParser( | |
description="Run a simple HTTP server that prints incoming requests." | |
) | |
parser.add_argument( | |
"port", | |
type=int, | |
nargs='?', | |
default=8001, | |
help="The port the HTTP server listens on.", | |
) | |
args = parser.parse_args() | |
print(f"Listening on localhost:{args.port}") | |
server = HTTPServer(("", args.port), RequestHandler) | |
server.serve_forever() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment