Skip to content

Instantly share code, notes, and snippets.

@orip
Forked from phrawzty/2serv.py
Last active February 19, 2024 13:42
Show Gist options
  • Save orip/28fbf579cc7326058c2e8ddc50b17e67 to your computer and use it in GitHub Desktop.
Save orip/28fbf579cc7326058c2e8ddc50b17e67 to your computer and use it in GitHub Desktop.
simple python http server to dump request headers
#!/usr/bin/env python3
import http
import http.server
import socketserver
import sys
def _log(s):
print(s)
class LoggingHandler(http.server.BaseHTTPRequestHandler):
def _consume_request_body(self):
try:
nbytes = int(self.headers.get("content-length"))
except (TypeError, ValueError):
return
if nbytes > 0:
self.rfile.read(nbytes)
def _handle_request(self):
_log(f"Handling {self.command} request")
_log("Headers:")
_log(self.headers)
self._consume_request_body()
self.send_response(http.HTTPStatus.OK)
self.send_header("X-Foo", "Bar")
self.end_headers()
self.wfile.write(b"Hi there")
for verb in "GET HEAD POST PUT DELETE CONNECT OPTIONS TRACE PATCH".split():
exec(f"def do_{verb}(self): return self._handle_request()")
class Server(socketserver.TCPServer):
allow_reuse_address = True
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser()
parser.add_argument(
"port",
default=8000,
type=int,
nargs="?",
help="bind to this port " "(default: %(default)s)",
)
args = parser.parse_args()
with Server(("", args.port), LoggingHandler) as httpd:
print(f"Serving HTTP on port {args.port}")
try:
httpd.serve_forever()
except KeyboardInterrupt:
print("\nKeyboard interrupt received, exiting.")
sys.exit(0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment