Trying to read headers in twisted middle proxy server.
Here you can see simple twisted server (stolen from stackoverflow, yeah...). It nicely works, but I need to switch proxies based on request headers. Can't understand where I can get headers here. It workd with hard coded proxie server but the idea is to switch proxies based on requests.
Any ideas please? Thanks for your time. Here is the code:
#!/usr/bin/env python
LISTEN_PORT = 8080
SERVER_PORT = 3128
SERVER_ADDR = "89.40.127.96"
from twisted.internet import protocol, reactor
class ServerProtocol(protocol.Protocol):
def __init__(self):
self.buffer = None
self.client = None
def connectionMade(self):
factory = protocol.ClientFactory()
factory.protocol = ClientProtocol
factory.server = self
reactor.connectTCP(SERVER_ADDR, SERVER_PORT, factory)
# Client => Proxy
def dataReceived(self, data):
if self.client:
self.client.write(data)
else:
self.buffer = data
# Proxy => Client
def write(self, data):
self.transport.write(data)
class ClientProtocol(protocol.Protocol):
def connectionMade(self):
self.factory.server.client = self
self.write(self.factory.server.buffer)
self.factory.server.buffer = ''
# Server => Proxy
def dataReceived(self, data):
self.factory.server.write(data)
# Proxy => Server
def write(self, data):
if data:
self.transport.write(data)
def main():
factory = protocol.ServerFactory()
factory.protocol = ServerProtocol
reactor.listenTCP(LISTEN_PORT, factory)
print "server"
reactor.run()
if __name__ == '__main__':
main()