Skip to content

Instantly share code, notes, and snippets.

@progrium
Created October 24, 2010 04:09
Show Gist options
  • Select an option

  • Save progrium/643073 to your computer and use it in GitHub Desktop.

Select an option

Save progrium/643073 to your computer and use it in GitHub Desktop.
import collections
import time
import simplejson as json
from mongrel2 import handler
sender_id = "82209006-86FF-4982-B5EA-D1E29E55D482"
conn = handler.Connection(sender_id, "ipc://run/requests", "ipc://run/responses")
listeners = collections.defaultdict(list)
HTTP_FORMAT = "HTTP/1.1 %(code)s %(status)s\r\n%(headers)s\r\n\r\n%(body)s"
HTTP_CHUNK = "%(size)s\r\n%(body)s\r\n"
def http_response(body, code, status, headers):
payload = {'code': code, 'status': status, 'body': body}
payload['headers'] = "\r\n".join('%s: %s' % (k,v) for k,v in
headers.items())
return HTTP_FORMAT % payload
def http_chunk(body):
payload = {'body': body, 'size': hex(len(body))[2:]}
return HTTP_CHUNK % payload
while True:
print "Waiting..."
req = conn.recv()
if req.is_disconnect():
print "DISCONNECT %s" % req.path
continue
if req.headers['METHOD'] == 'GET':
print "listener on %s" % req.path
listeners[req.path].append(req.conn_id)
conn.reply(req, http_response(http_chunk("\n"), 200, "OK",
{'connection': 'keep-alive', 'transfer-encoding': 'chunked', 'content-type': 'text/plain'}))
continue
if req.headers['METHOD'] == 'POST':
print "publishing '%s' on %s" % (req.body, req.path)
print listeners[req.path]
print http_chunk(req.body)
conn.deliver(req.sender, listeners[req.path], http_chunk(req.body))
conn.reply_http(req, "Sent\n", 200, "OK")
continue
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment