Created
December 5, 2020 13:51
-
-
Save adiroiban/ef9dfd2cce5c59b70e1bc0600b58adeb to your computer and use it in GitHub Desktop.
Example of failing an HTTP proxy request in Twisted.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
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