Search code examples
pythonmitmproxy

Raw request and response to HTTPRequest and HTTPResponse, respectively


I've been exploring the codebase for the last few weeks and I have yet to been able to find how to convert raw bytes to HTTPRequest or HTTPResponse.

Long story short, I would like to do something along the lines of (simplified for question sake):

from mitmproxy.http import HTTPRequest

req = b"GET / HTTP/1.1\r\nHost: example.com\r\nConnection: keep-alive\r\nAccept: */*\r\n\r\n"

http_request = HTTPRequest.create(req)

print(http_request.method) 
# >>> GET

I'm 99% certain somewhere in the code base such actions must take place, but I've yet to find it. Any help would be awesome.


Solution

  • Parsing is done in https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/net/http/http1/read.py and https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/net/http/http1/read_sansio.py. Note that the latter will be merged in the former in a few days (we're just in the middle of a major restructuring) and some of the methods currently in read.py will disappear.