def handleHttpRequest(request: Request, root: str) -> Response: if request.url == '': return Response() needBody = False if request.method == 'GET': needBody = True elif request.method == 'HEAD': needBody = False else: return closeConnection(Response(status=statuses[405])) isDir = False path = root + request.url if request.url[-1] == '/': isDir = True path += 'index.html' if path.find('../') != -1: return closeConnection(Response(status=statuses[403])) resp = Response() if needBody: try: with open(path, 'rb') as file: resp.body = file.read() resp.addHeader('Content-Length', str(len(resp.body))) except FileNotFoundError: if isDir: return closeConnection(Response(status=statuses[403])) else: return closeConnection(Response(status=statuses[404])) else: resp.addHeader('Content-Length', str(os.lstat(path).st_size)) resp.addHeader('Content-Type', defineContentType(path)) return closeConnection(resp)