def server(): """Simple socket server that uses httpsuite to interpret and reply. 1. Opens a new socket. 2. Binds to 127.0.0.1:8080 and waits until new connection. 3. Accepts connection from external source. 4. Receive the data from the client. 5. Parse the clients request. 6. Interpret the request. 7. Reply to the client. 8. Close the connection with the client. """ # 1. Opens a new socket. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 2. Binds to 127.0.0.1:8080 and waits until new connection. s.bind(("127.0.0.1", 8080)) s.listen(1) # 3. Accepts connection from external source. conn, address = s.accept() print("===== Connecting With New Client =====", "\n") print(address, "\n") # 4. Receive the data from the client. data = conn.recv(1024) # 5. Parse the clients request. request = Request.parse(data) print("===== Received Data From Client =====", "\n") print(request, "\n") # 6. Interpret the request. response = Response(protocol="HTTP/1.1", status=200, status_msg="OK") if request.target == "/": response.body = "Homepage of the microservice." elif request.target == "/data": response.body = "You are accessing the /data directory of this microservice." else: response.status = 404 response.status_msg = "Not Found" print("===== Replying to Client =====", "\n") print(response, "\n") # 7. Reply to the client. conn.sendall(response.raw) print("===== Closing Connection to Client =====", "\n") # 8. Close the connection with the client, and the server. conn.close() s.close()
def test_request_str(self): parsed = Request.parse(request_raw) assert isinstance(parsed, Request) assert parsed.method == "POST" assert parsed.target == "/" assert parsed.protocol == "HTTP/1.1" assert parsed.headers == Headers({ "Host": "www.google.com", "Accept": "*/*", "User-Agent": "httpsuite/1.0.0", "Connection": "keep-alive", }) assert parsed.body == '{"hello": "world"}'