Skip to content

Instantly share code, notes, and snippets.

@etianen
Created March 31, 2010 16:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save etianen/350574 to your computer and use it in GitHub Desktop.
Save etianen/350574 to your computer and use it in GitHub Desktop.
import sys, itertools
# Supported HTTP methods.
GET = "GET"
POST = "POST"
# A parsed HTTP request.
class Request(object):
def __init__(self, method, path, protocol, headers):
self.method = method
self.path = path
self.protocol = protocol
self.headers = headers
# A parser for a HTTP request.
def parse_header(line):
return (item.strip() for item in line.split(":", 1))
def parse(input):
lines = iter(input)
method, path, protocol = next(lines).split()
headers = dict(parse_header(line) for line in itertools.takewhile(lambda line: line != "", lines))
return Request(method, path, protocol, headers)
# Known HTTP status messages.
status_messages = {200: "OK",
404: "Not Found",
500: "Server Error"}
# A HTTP response.
class HttpResponse(object):
def __init__(self, code, body):
self.code = code
self.body = body
def __str__(self):
return "%i %s\n\n%s" % (self.code, status_messages.get(self.code, ""), self.body)
# Request handler.
def request_handler(request):
body = "<h1>Result for a %s request to http://%s%s</h1>\n%s" % (request.method, request.headers["Host"], request.path, request.headers)
return HttpResponse(200, body)
# Main server method used to process a single request.
def processRequest(input):
return str(request_handler(parse(input)))
if __name__ == "__main__":
print processRequest(sys.stdin)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment