Skip to content

Instantly share code, notes, and snippets.

@lucky
Created December 16, 2010 00:22
Show Gist options
  • Save lucky/742828 to your computer and use it in GitHub Desktop.
Save lucky/742828 to your computer and use it in GitHub Desktop.
Returns back exactly what you sent. Requires eventlet.
import eventlet
import traceback
from eventlet.greenio import socket
CRLF = "\r\n"
CRLF_2 = CRLF * 2
def _handler(sock, addr):
print "Got client on %s" % (addr,)
sock.settimeout(10)
full_data = ""
headers_done = None
headers = {}
while not headers_done:
data = sock.recv(8192)
full_data += data
headers_done = CRLF_2 in full_data
header_data, body = full_data.split(CRLF_2, 1)
for line in header_data.split(CRLF, 1)[1:]:
k, v = line.split(":", 1)
headers[k] = v
if 'Content-Length' in headers:
full_body_length = int(headers['Content-Length'])
leftover = full_body_length - len(body)
if leftover > 0:
full_data += sock.recv(leftover, socket.MSG_WAITALL)
response = """HTTP/1.1 200 OK\r
Content-Type: text/plain\r
Content-Length: %d\r
\r
%s""" % (len(full_data), full_data)
sock.sendall(response)
sock.close()
def handler(sock, addr):
try:
_handler(sock, addr)
except Exception as e:
traceback.print_exc()
sock.close()
def main():
listener = eventlet.listen(('0.0.0.0', 8080))
eventlet.serve(listener, handler)
if __name__ == '__main__':
print "Starting up"
try:
main()
except KeyboardInterrupt:
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment