|
| 1 | +# mHTTP - A simple HTTP server |
| 2 | +# Written by M.V.Harish Kumar on 24/10/2023 |
| 3 | + |
| 4 | +import sys, socket |
| 5 | +from pathlib import Path |
| 6 | + |
| 7 | +HOST = "0.0.0.0" |
| 8 | +PORT = 1997 |
| 9 | +FOLDER = '.' if len(sys.argv) < 2 else sys.argv[1] |
| 10 | + |
| 11 | +def get_content(path): |
| 12 | + ext = "html" |
| 13 | + match path: |
| 14 | + case "/": |
| 15 | + try: |
| 16 | + with open(FOLDER + "/index.html", "r") as f: |
| 17 | + content = f.read() |
| 18 | + except FileNotFoundError: |
| 19 | + content = "The Server is working! but there is no index.html file to render" |
| 20 | + case _: |
| 21 | + try: |
| 22 | + with open(FOLDER + path, "r") as f: |
| 23 | + if Path(FOLDER + path).suffix != ".html": |
| 24 | + ext = "plain" |
| 25 | + content = f.read() |
| 26 | + except FileNotFoundError: |
| 27 | + return 404, "File not found", ext |
| 28 | + return 200, content, ext |
| 29 | + |
| 30 | +with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: |
| 31 | + try: |
| 32 | + s.bind((HOST, PORT)) |
| 33 | + s.listen() |
| 34 | + |
| 35 | + print("mHTTP: The Micro-HTTP Server") |
| 36 | + print(f"Server Started running at {HOST}:{PORT}\n") |
| 37 | + print("mhttp: waiting for connections...") |
| 38 | + |
| 39 | + while True: |
| 40 | + clnt, caddr = s.accept() |
| 41 | + with clnt: |
| 42 | + print(f"mhttp: got connection from {caddr[0]}:{caddr[1]}") |
| 43 | + req = clnt.recv(1024).decode() |
| 44 | + if not req: |
| 45 | + print("mhttp: connection closed unexpectedly", file=sys.stderr) |
| 46 | + break |
| 47 | + |
| 48 | + req = req.split("\r\n") |
| 49 | + print(f"mhttp: got request: {req[0]}") |
| 50 | + path = req[0].split(" ")[1] |
| 51 | + |
| 52 | + sts_cd, content, ftype = get_content(path) |
| 53 | + |
| 54 | + resp = f"HTTP/1.1 {sts_cd}\r\n" \ |
| 55 | + f"Content-Type: text/{ftype}\r\n" \ |
| 56 | + "\r\n" + content |
| 57 | + |
| 58 | + clnt.sendall(resp.encode()) |
| 59 | + print(f"mhttp: sent response({sts_cd}) to {caddr[0]}:{caddr[1]}") |
| 60 | + except KeyboardInterrupt: |
| 61 | + print("mhttp: Got Keyboard Interrupt", file=sys.stderr) |
| 62 | + print("mhttp: Closing Connection.", file=sys.stderr) |
| 63 | + |
| 64 | + |
0 commit comments