Created
May 31, 2023 20:03
-
-
Save geonnave/cec71e4542db206969859701306723da to your computer and use it in GitHub Desktop.
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
import servidor_caseiro, json | |
produtos = [ | |
"Banana", | |
"Maçã", | |
"Laranja", | |
] | |
def ler_carrinho(method, path, request_body): | |
return "<h1>Carrinho de compras</h1>", "200 OK" | |
def adicionar_carrinho(method, path, request_body): | |
body = json.loads(request_body) | |
if body["produto"] in produtos: | |
return "<h1>Adicionado ao carrinho</h1>", "200 OK" | |
else: | |
return "<h1>Produto não encontrado</h1>", "400 Bad Request" | |
def pagina_principal(method, path, request_body): | |
return "<h1>Página principal</h1>", "200 OK" | |
router = { | |
("GET", '/'): pagina_principal, | |
("GET", '/carrinho'): ler_carrinho, | |
("POST", '/carrinho'): adicionar_carrinho, | |
} | |
if __name__ == '__main__': | |
servidor_caseiro.start_server(router) |
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
import socket | |
def handle_request(request, router): | |
print(">>>>>>>>> Request: ", request) | |
request = request.split('\n') | |
method, path, version = request[0].split(' ') | |
method = method.strip() | |
path = path.strip() | |
request_body = request[-1] | |
router_function = router.get((method, path), None) | |
if router_function: | |
body, status = router_function(method, path, request_body) | |
else: | |
body = f"<h1>Route {path} found in this server</h1>" | |
status = "404 Not Found" | |
response = f"""HTTP/1.1 {status} | |
Content-Type: text/html; charset=utf-8 | |
{body}""" | |
return response | |
def start_server(router): | |
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | |
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) | |
server_socket.bind(('localhost', 8000)) | |
server_socket.listen(1) | |
print('Server listening on port 8000') | |
while True: | |
client_socket, addr = server_socket.accept() | |
request = client_socket.recv(2048).decode() | |
response = handle_request(request, router) | |
client_socket.sendall(response.encode()) | |
client_socket.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment