import re
from http_parser.http import HttpStream, NoMoreData
from http_parser.reader import SocketReader
import socket

def rewrite_headers(parser, values=None):
    try:
        headers = parser.headers()
        if isinstance(values, dict):
            headers.update(values)

        httpver = "HTTP/%s" % ".".join(map(str, 
                    parser.version()))

        new_headers = ["%s %s %s\r\n" % (parser.method(), parser.url(), 
            httpver)]

        new_headers.extend(["%s: %s\r\n" % (k, str(v)) for k, v in \
                headers.items()])

        return "".join(new_headers) + "\r\n"
    except NoMoreData:
        return


def rewrite_request(req):
    try: 
        while True:
            parser = HttpStream(req)
                
            new_headers = rewrite_headers(parser, {'Host': 'gunicorn.org'})
            if new_headers is None:
                break
            req.send(new_headers)
            body = parser.body_file()
            while True:
                data = body.read(8192)
                if not data:
                    break
                req.send(data)
            if not parser.should_keep_alive():
                print "don't keep alive"
                break
    except socket.error:
        pass


def rewrite_response(resp):
    while True:
        parser = HttpStream(resp)
        # we aren't doing anything here
        for data in parser:
            resp.send(data)
 
        if not parser.should_keep_alive():
            # close the connection.
            break

def proxy(data):
    return {'remote': ('gunicorn.org', 80)}

@@ -160,21 +160,8 @@
 e):%0A
-    try:%0A    
     
@@ -187,20 +187,16 @@
 aders()%0A
-    
     if i
@@ -220,36 +220,32 @@
  dict):%0A        
-    
 headers.update(v
@@ -252,28 +252,24 @@
 alues)%0A%0A    
- 
-   
 httpver = %22H
@@ -309,28 +309,24 @@
             
-    
 parser.versi
@@ -333,20 +333,16 @@
 on()))%0A%0A
-    
     new_
@@ -410,20 +410,16 @@
         
-    
 httpver)
@@ -421,20 +421,16 @@
 pver)%5D%0A%0A
-    
     new_
@@ -494,28 +494,24 @@
             
-   
- 
 headers.item
@@ -517,20 +517,16 @@
 ms()%5D)%0A%0A
-    
     retu
@@ -562,47 +562,8 @@
 %5Cn%22%0A
-    except NoMoreData:%0A        return%0A%0A
 %0Adef
@@ -1145,16 +1145,17 @@
  except 
+(
 socket.e
@@ -1158,16 +1158,29 @@
 et.error
+, NoMoreData)
 :%0A      
@@ -1216,16 +1216,29 @@
 (resp):%0A
+    try:%0A    
     whil
@@ -1245,32 +1245,36 @@
 e True:%0A        
+    
 parser = HttpStr
@@ -1283,16 +1283,20 @@
 m(resp)%0A
+    
         
@@ -1327,16 +1327,20 @@
 ng here%0A
+    
         
@@ -1371,16 +1371,20 @@
         
+    
 resp.sen
@@ -1392,17 +1392,25 @@
 (data)%0A 
-%0A
+    %0A    
         
@@ -1456,16 +1456,20 @@
         
+    
 # close 
@@ -1496,21 +1496,77 @@
         
+    
 break
+%0A    except (socket.error, NoMoreData):%0A        pass
 %0A%0Adef pr

improve example