Created
January 12, 2021 13:04
-
-
Save shivams/86c9e36222ae6be27a6ec35846669ff0 to your computer and use it in GitHub Desktop.
This is a simple HTTP server developed for Recurse Center's application.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
#((2021-01-12)) For Recurse Center | |
import socket | |
import re | |
SERVER_HOST = "localhost" | |
SERVER_PORT = 4000 | |
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | |
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) | |
server_socket.bind((SERVER_HOST, SERVER_PORT)) | |
server_socket.listen(1) | |
print(f"Listening on port {SERVER_PORT}...") | |
http_200 = "HTTP/1.0 200 OK\n\n" #OK | |
http_400 = "HTTP/1.0 400 OK\n\n" #Syntax Error | |
http_404 = "HTTP/1.0 404 OK\n\n" #Path Error | |
#This is our memory storage | |
storage = dict() | |
def processAction(action, path): | |
''' | |
This function processes get and set actions | |
Inputs: | |
action: get or set | |
path: path requested by the client | |
''' | |
keyvalues = re.search(rf"/{action}\?(\w+)\=(\w+)", path) | |
#First, extract key and value from the path | |
if keyvalues: | |
key, value = keyvalues[1], keyvalues[2] | |
else: | |
response = http_400 + f"Received {action} request but it's a bad one and can't be processed" | |
return response #Return early. No point in further processing | |
#Process GET and SET | |
if action == 'get' and key == 'key': #For correctly formatted GET | |
response = http_200 + f"Received {action} request with key {keyvalues[1]} and value {keyvalues[2]}" | |
if value in storage: | |
respValue = storage[value] | |
response += f"\nValue for the requested key {value} is {respValue}" | |
else: | |
response += "\nAlas! No values found for the requested key" | |
elif action == 'get': #For incorrectly formatted GET | |
response = http_400 + f"Received {action} request but it's badly formatted." | |
else: #For SET | |
storage[key] = value | |
response = http_200 + f"Received {action} request with key {keyvalues[1]} and value {keyvalues[2]}" | |
response += "\nSET values successfully" | |
return response | |
while True: | |
client_connection, client_address = server_socket.accept() | |
request = client_connection.recv(1024).decode() | |
path = request.split('\n')[0].split()[1] | |
print(path) | |
if path == "/": | |
response = http_200 + "Hello World" | |
elif "/set" in path: | |
response = processAction('set', path) | |
elif "/get" in path: | |
response = processAction('get', path) | |
else: | |
response = http_404 + "That's a 404. Path not known to server." | |
client_connection.sendall(response.encode()) | |
client_connection.close() | |
server_socket.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment