front_demo/main.py

64 lines
1.6 KiB
Python
Raw Normal View History

2025-01-13 14:04:52 +03:00
from http.server import BaseHTTPRequestHandler, HTTPServer
from http.client import HTTPMessage
import requests
from config.main_local import pool
from daemon.SimpleDaemon import Daemon
hostName = "localhost"
serverPort = 9000
class FrontDemoDaemon(Daemon):
def run(self):
webServer = HTTPServer((hostName, serverPort), MyServer)
print(f"Server started http://{hostName}:{serverPort}")
try:
webServer.serve_forever()
except KeyboardInterrupt:
pass
webServer.server_close()
print("Http server stopped.")
class MyServer(BaseHTTPRequestHandler):
def do_GET(self):
host = get_host_from_headers(self.headers)
subdomain = get_subdomain(host)
port = get_port(subdomain)
url = 'http://localhost:{port}{path}'.format(path=self.path, port=port)
response = requests.get(url)
self.send_response(200)
self.send_header("Content-type", response.headers.get("Content-type"))
self.end_headers()
self.wfile.write(bytes(response.text, "utf-8"))
def get_host_from_headers(headers: HTTPMessage):
for item in headers.items():
if item[0] == "Host":
return item[1]
return None
def get_subdomain(host: str):
res = host.split(sep=".", maxsplit=-1)
if res[0]:
return res[0]
return None
def get_port(subdomain: str):
for item in pool:
if item[0] == subdomain:
return item[1]
return None
if __name__ == "__main__":
with FrontDemoDaemon('/tmp/front-demo-daemon.pid', error_log_file='/var/log/front-demo-daemon.txt') as front:
front.process_command()