Skip to content

Instantly share code, notes, and snippets.

@adiroiban
Created December 5, 2020 13:51
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adiroiban/ef9dfd2cce5c59b70e1bc0600b58adeb to your computer and use it in GitHub Desktop.
Save adiroiban/ef9dfd2cce5c59b70e1bc0600b58adeb to your computer and use it in GitHub Desktop.
Example of failing an HTTP proxy request in Twisted.
"""
In one terminal
$ $ python3 twisted_fail_http_proxy_request.py
In another terminal test it with:
$ curl -v -x http://localhost:8000 http://httpforever.com/
"""
from twisted.web import proxy, http
from twisted.internet import reactor
class YourProxyRequestHandler(proxy.ProxyRequest):
"""
This is the request handler for a proxy request.
"""
def process(self):
if True:
return self._fail()
# Do the real processing.
return super().process()
def _fail(self):
"""
Return a failure.
"""
s = self.content.read()
self.setResponseCode(400)
self.setHeader(b'connection', b'close')
self.write(b'We decided to fail.')
self.finish() # or just lose the connection.
class ProxyFactory(http.HTTPFactory):
def buildProtocol(self, addr):
p = proxy.Proxy()
p.requestFactory = YourProxyRequestHandler
return p
reactor.listenTCP(8000, ProxyFactory())
reactor.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment