Skip to content

Instantly share code, notes, and snippets.

@imduffy15
Created March 30, 2020 19:13
Show Gist options
  • Save imduffy15/3412d7fc7e2e755e3d2be552313a8016 to your computer and use it in GitHub Desktop.
Save imduffy15/3412d7fc7e2e755e3d2be552313a8016 to your computer and use it in GitHub Desktop.
import json
from http.client import HTTPResponse
from http.server import BaseHTTPRequestHandler
from io import BytesIO
class HTTPRequest(BaseHTTPRequestHandler):
def __init__(self, request):
BaseHTTPRequestHandler.__init__(self, request, "127.0.0.1", None)
def setup(self):
self.wfile = BytesIO()
self.rfile = BytesIO(self.request)
self.body = "{}"
def handle_one_request(self):
self.raw_requestline = self.rfile.readline(65537)
if not self.parse_request():
# An error code has been sent, just exit
return
try:
content_length = int(self.headers["Content-Length"])
self.body = self.rfile.read(content_length).decode("utf-8")
except:
pass
def finish(self):
pass
class FakeSocket(object):
def __init__(self, response_bytes):
self._file = BytesIO(response_bytes)
def makefile(self, *args, **kwargs):
return self._file
def parse_response(response_bytes):
resp = HTTPResponse(FakeSocket(response_bytes))
resp.begin()
return resp
with open("full-body.txt", "rb") as fp:
while True:
header = fp.readline()
if not header:
break
print("# Request:")
print("```json")
headerParts = header.decode().split(" ")
request_size = int(headerParts[0])
response_size = int(headerParts[1])
req = HTTPRequest(fp.read(request_size))
print(json.dumps(json.loads(req.body), indent=4))
print("```")
fp.read(1) # skip over CRLF
print("# Response:")
print("```json")
try:
res = parse_response(fp.read(response_size)).read()
if res:
print(json.dumps(json.loads(res.decode("utf-8")), indent=4))
except:
pass
print("```")
fp.read(1) # skip over CRLF
print("\n___")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment