#!/usr/bin/env python3 import sys import http.server import socket __version__ = "0.1" class EchoHTTPRequestHandler(http.server.BaseHTTPRequestHandler): server_version = "EchoHTTP/" + __version__ def do_HEAD(self): """Echo a HEAD request""" self.echo_request() def do_GET(self): """Echo a GET request""" self.echo_request() def do_POST(self): """Echo a POST request""" self.echo_request() def do_PUT(self): """Echo a PUT request""" self.echo_request() def do_DELETE(self): """Echo a DELETE request""" self.echo_request() def do_CONNECT(self): """Echo a CONNECT request""" self.echo_request() def do_OPTIONS(self): """Echo a OPTIONS request""" self.echo_request() def do_TRACE(self): """Echo a TRACE request""" self.echo_request() def do_PATCH(self): """Echo a PATCH request""" self.echo_request() def echo_headers(self): """Echo a the headers of a request""" for key, val in self.headers.items(): header: str = f'{key}: {val}\n' self.wfile.write(header.encode('utf-8')) def echo_body(self): length = int(self.headers.get('Content-Length', 0)) if length == 0: return body = self.rfile.read(length) self.wfile.write(body) def echo_request(self): self.send_response(200) self.send_header('Content-Type', 'text/plain') self.end_headers() self.echo_headers() self.wfile.write(b'-'*20) self.wfile.write(b'\n') self.echo_body() def launch(address: str, port: int): handler = EchoHTTPRequestHandler *_, addr = socket.getaddrinfo(address, port, type=socket.SOCK_STREAM, flags=socket.AI_PASSIVE)[0] with http.server.ThreadingHTTPServer(addr, handler) as httpd: host, port = httpd.server_address print(f"Echoing HTTP on {host}:{port}") try: httpd.serve_forever() except KeyboardInterrupt: print("\nRecieved Keyboard Interput, exitting.") sys.exit(0) if __name__ == "__main__": import argparse parser = argparse.ArgumentParser( description='A simple http echo server' ) parser.add_argument('-b', '--bind', metavar='ADRESS', help='bind to this address ' '(default: all interfaces)') parser.add_argument('port', default=8000, type=int, nargs='?', help='bind to this port ' '(default: %(default)s)') args = parser.parse_args() launch(args.bind, args.port)