Created
July 10, 2022 23:00
-
-
Save andreburto/18ef8e9db2aa8bd76c71f12965aabb65 to your computer and use it in GitHub Desktop.
Tiny web server that can eventually run on my phone.
This file contains hidden or 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
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<title>Server</title> | |
</head> | |
<body> | |
<h1>Server</h1> | |
<p>This is a test.</p> | |
</body> | |
</html> |
This file contains hidden or 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 http.server as hs | |
import logging | |
import os | |
import sys | |
DEFAULT_FILE = "index.html" | |
logger = logging.getLogger(__file__) | |
logger.addHandler(logging.StreamHandler(sys.stdout)) | |
logger.setLevel(logging.INFO) | |
class web_handler(hs.BaseHTTPRequestHandler): | |
def load_file(self, file): | |
if not os.path.isfile(file): | |
return 404, "404".encode("utf-8") | |
else: | |
with open(file, 'rb') as fh: | |
return 200, fh.read() | |
def do_GET(self): | |
file = f"/{DEFAULT_FILE}" if self.path == "/" else self.path | |
status_code, file_contents = self.load_file(f"{os.path.curdir}{file}") | |
self.send_response(status_code) | |
self.send_header("Content-type", "text/html") | |
self.end_headers() | |
self.wfile.write(file_contents) | |
class web_server(hs.HTTPServer): | |
def __init__(self, handler, address="", port=8000): | |
super().__init__((address, port), handler) | |
def main(): | |
try: | |
ws = web_server(web_handler) | |
ws.serve_forever() | |
except Exception as ex: | |
print(f"{ex}") | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment