Skip to content

Instantly share code, notes, and snippets.

@parrotmac
Created June 8, 2021 05:01
Show Gist options
  • Select an option

  • Save parrotmac/8a8b45f3dd14ea1951c6693152ac2095 to your computer and use it in GitHub Desktop.

Select an option

Save parrotmac/8a8b45f3dd14ea1951c6693152ac2095 to your computer and use it in GitHub Desktop.
Modify HTTP requests & responses with Mitmproxy
"""HTTP-specific events."""
import mitmproxy.http
class Events:
filter = "news.ycombinator.com"
def http_connect(self, flow: mitmproxy.http.HTTPFlow):
"""
An HTTP CONNECT request was received. Setting a non 2xx response on
the flow will return the response to the client abort the
connection. CONNECT requests and responses do not generate the usual
HTTP handler events. CONNECT requests are only valid in regular and
upstream proxy modes.
"""
def requestheaders(self, flow: mitmproxy.http.HTTPFlow):
"""
HTTP request headers were successfully read. At this point, the body
is empty.
"""
def request(self, flow: mitmproxy.http.HTTPFlow):
"""
The full HTTP request has been read.
"""
def responseheaders(self, flow: mitmproxy.http.HTTPFlow):
"""
HTTP response headers were successfully read. At this point, the body
is empty.
"""
def response(self, flow: mitmproxy.http.HTTPFlow):
if 'text/html' in flow.response.headers['Content-Type']:
# Replace some inline coloring (get a nice blue instead of HN orange)
#flow.response.content = flow.response.content.replace(b'#ff6600', b'#0099ff')
# Modify HTML <head> to include another CSS source
darkmode = b'<style>body,#hnmain,textarea,input { background-color: #222222 !important; color: #eaeaea !important; } a,a:link,a:visited,.commtext,.reply { color: #eaeaea !important; }</style></head>'
flow.response.content = flow.response.content.replace(b'</head>', darkmode)
def error(self, flow: mitmproxy.http.HTTPFlow):
"""
An HTTP error has occurred, e.g. invalid server responses, or
interrupted connections. This is distinct from a valid server HTTP
error response, which is simply a response with an HTTP error code.
"""
addons = [Events()]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment