Skip to content

Instantly share code, notes, and snippets.

@winstxnhdw
Last active September 1, 2023 03:42
Show Gist options
  • Save winstxnhdw/0492a1ed69185711388716acaadb018d to your computer and use it in GitHub Desktop.
Save winstxnhdw/0492a1ed69185711388716acaadb018d to your computer and use it in GitHub Desktop.
A simple HTTP server that prints the request headers and JSON body to the console.
from http.server import HTTPServer, SimpleHTTPRequestHandler
from json import dumps, loads
from sys import argv
from typing import Literal
class Server(SimpleHTTPRequestHandler):
"""
Summary
-------
a simple HTTP server that prints the request headers and body to the console
Methods
-------
do_POST()
prints the request headers and body to the console
"""
def do_POST(self): # pylint: disable=invalid-name
"""
Summary
-------
prints the request headers and body to the console
"""
content_length = int(self.headers['Content-Length'])
post_data = self.rfile.read(content_length).decode('utf-8')
post_data_list = dumps(loads(post_data), indent=2).split('\n')
formatted_data = '\n'.join(line.strip() for line in post_data_list)
print(f"\nPOST\n{self.headers}Body:\n{formatted_data}")
self.send_response(404)
def parse_args() -> int | Literal[5000]:
"""
Summary
-------
parses the command line arguments
Returns
-------
port (int | 5000) : a port number from 1025 to 65536
"""
try:
return 5000 if len(argv) < 2 else int(argv[1])
except ValueError:
print("\nPort must be an integer.\ne.g. python server.py 5000\n")
raise
def init_server():
"""
Summary
-------
initializes the server
"""
port = parse_args()
host = 'localhost'
httpd = HTTPServer((host, port), Server)
try:
print(f"Serving HTTP on {host} port {port} (http://{host}:{port}/)..")
httpd.serve_forever()
except KeyboardInterrupt:
print("Manual exit detected.")
finally:
httpd.server_close()
print("\nServer closing..")
if __name__ == '__main__':
init_server()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment