Skip to content

Instantly share code, notes, and snippets.

@SXHRYU
Forked from 1kastner/reflect.py
Last active April 3, 2024 13:56
Show Gist options
  • Save SXHRYU/bd942958cfb41480c887857e7d0aaced to your computer and use it in GitHub Desktop.
Save SXHRYU/bd942958cfb41480c887857e7d0aaced to your computer and use it in GitHub Desktop.
ruffed & blacked. A simple echo server to inspect http web requests
# ruff: noqa: N802, N815, E501
# Reflects the requests from HTTP methods GET, POST, PUT, and DELETE
# Written by Nathan Hamiel (2010)
from http.server import BaseHTTPRequestHandler, HTTPServer
from optparse import OptionParser
class RequestHandler(BaseHTTPRequestHandler):
def do_GET(self) -> None:
request_path = self.path
print("\n----- Request Start ----->\n")
print("Request path:", request_path)
print("Request headers:", self.headers)
print("<----- Request End -----\n")
self.send_response(200)
self.send_header("Set-Cookie", "foo=bar")
self.end_headers()
def do_POST(self) -> None:
request_path = self.path
print("\n----- Request Start ----->\n")
print("Request path:", request_path)
request_headers = self.headers
content_length = request_headers.get("Content-Length")
length = int(content_length) if content_length else 0
print("Content Length:", length)
print("Request headers:", request_headers)
print("Request payload:", self.rfile.read(length))
print("<----- Request End -----\n")
self.send_response(200)
self.end_headers()
do_PUT = do_POST
do_DELETE = do_GET
def main() -> None:
port = 8080
print("Listening on 0.0.0.0:%s" % port)
server = HTTPServer(("", port), RequestHandler)
server.serve_forever()
if __name__ == "__main__":
parser = OptionParser()
parser.usage = (
"Creates an http-server that will echo out any GET or POST parameters\n"
"Run:\n\n"
" reflect"
)
(options, args) = parser.parse_args()
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment