#!/usr/bin/python

from twisted.protocols.basic import LineReceiver
from twisted.internet import reactor, protocol


class EchoHTTP(LineReceiver):
    """
    A protocol that echoes back bodyless HTTP requests as HTTP responses.
    """
    _result = ""

    def lineReceived(self, line):
        self._result += line + "\r\n"
        if not line:
            self.requestReceived(self._result)

    def requestReceived(self, request):
        self.transport.write(
            "HTTP/1.0 200 OK\r\n"
            "Content-Type: text/plain\r\n"
            "Content-Length: %d\r\n"
            "\r\n%s" % (len(request), request))
        self.transport.loseConnection()


class EchoFactory(protocol.ServerFactory):
    """
    A factory that creates EchoHTTP() protocol instances.
    """
    def buildProtocol(self, addr):
        return EchoHTTP()


if __name__ == '__main__':
    print "Starting web server at <http://localhost:1234/> ..."
    reactor.listenTCP(1234, EchoFactory())
    reactor.run()
