processRequest.py 1.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
import sys
import json
import datetime
import re

infile = sys.argv[1]


def GetHeader(content, code):
    return "HTTP/1.1 {0}\r\nDate:{1}\r\nServer:Fake Python Server\r\nContent-Length: {2}\r\nConnection: Closed\r\nContent-Type: text/html\r\n\r\n".format(code, datetime.datetime.now(), len(content));

def ReturnError (errorMessage, sliceA = 2, sliceB = 3):
    return { "slices" : [
        {
            "slice"         : sliceA,
            "slicePurpose"  : "Header",
            "data"          : GetHeader(errorMessage, "500 Internal Server Error") 
        },
        {
            "slice"         : sliceB,
            "slicePurpose"  : "Content",
            "data"          : errorMessage
        }
        ]}


with open(infile) as f:
    request = json.loads(f.read())

    inputSlices = request["slices"]
    headerSlice = inputSlices[0]
    contentSlice = inputSlices[1]

    p = re.compile('GET (.*) HTTP\/1.1')
    r = p.match(headerSlice["data"])
    url = r.group(0)

    responseContent = "<html><body><h1>Hello World</h1><p>Middlebox Hackathon Demo #2</p><p>You requested URL {0}</body></html>".format(url)

    response = { "slices" : [
        {
            "slice"         : headerSlice["slice"],
            "slicePurpose"  : headerSlice["slicePurpose"],
            "data"          : GetHeader(responseContent, "200 OK") 
        },
        {
            "slice"         : contentSlice["slice"],
            "slicePurpose"  : contentSlice["slicePurpose"],
            "data"          : responseContent
        }
        ]
    }

print (json.dumps(response))