Files
mtusi2026lab2/scripts/serve_web.py
T

140 lines
4.5 KiB
Python
Executable File
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""Локальный UI lab2: статика из web/ + прокси /api и /health на API.
Зачем прокси: браузерный origin у UI другой, чем у API (:8080), CORS в бэкенде нет.
Прокси делает один origin — запросы идут как с того же хоста.
python3 scripts/serve_web.py
# открыть http://127.0.0.1:5173
Переменные:
WEB_PORT — порт UI (по умолчанию 5173)
API_URL — upstream API (по умолчанию http://127.0.0.1:8080)
"""
from __future__ import annotations
import http.client
import os
import sys
import urllib.parse
from functools import partial
from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
WEB = ROOT / "web"
API = os.environ.get("API_URL", "http://127.0.0.1:8080").rstrip("/")
PORT = int(os.environ.get("WEB_PORT", "5173"))
class Handler(SimpleHTTPRequestHandler):
def __init__(self, *args, **kwargs):
super().__init__(*args, directory=str(WEB), **kwargs)
def log_message(self, fmt: str, *args) -> None:
sys.stderr.write("%s - %s\n" % (self.address_string(), fmt % args))
def do_GET(self): # noqa: N802
if self._is_api():
self._proxy()
return
return super().do_GET()
def do_POST(self): # noqa: N802
if self._is_api():
self._proxy()
return
self.send_error(405)
def do_DELETE(self): # noqa: N802
if self._is_api():
self._proxy()
return
self.send_error(405)
def do_OPTIONS(self): # noqa: N802
if self._is_api():
self._proxy()
return
self.send_error(405)
def _is_api(self) -> bool:
path = urllib.parse.urlparse(self.path).path
return path.startswith("/api/") or path.startswith("/health/")
def _proxy(self) -> None:
parsed = urllib.parse.urlparse(API)
host = parsed.hostname or "127.0.0.1"
port = parsed.port or (443 if parsed.scheme == "https" else 80)
conn_cls = http.client.HTTPSConnection if parsed.scheme == "https" else http.client.HTTPConnection
length = int(self.headers.get("Content-Length", "0") or 0)
body = self.rfile.read(length) if length else None
headers = {}
for key in ("Authorization", "Content-Type", "Accept", "X-Request-Id"):
val = self.headers.get(key)
if val:
headers[key] = val
# Login: тело должно быть реально пустым — не подставляем Content-Type зря.
if body is None and "Content-Type" in headers and self.command == "POST":
# оставляем как прислал клиент
pass
try:
conn = conn_cls(host, port, timeout=30)
conn.request(self.command, self.path, body=body, headers=headers)
upstream = conn.getresponse()
payload = upstream.read()
except OSError as exc:
msg = ("upstream unavailable: %s" % exc).encode()
self.send_response(502)
self.send_header("Content-Type", "text/plain; charset=utf-8")
self.send_header("Content-Length", str(len(msg)))
self.end_headers()
self.wfile.write(msg)
return
self.send_response(upstream.status)
hop_by_hop = {
"connection",
"keep-alive",
"proxy-authenticate",
"proxy-authorization",
"te",
"trailers",
"transfer-encoding",
"upgrade",
"content-encoding",
"content-length",
}
for key, val in upstream.getheaders():
if key.lower() in hop_by_hop:
continue
self.send_header(key, val)
self.send_header("Content-Length", str(len(payload)))
self.end_headers()
if self.command != "HEAD":
self.wfile.write(payload)
conn.close()
def main() -> int:
if not WEB.is_dir():
print("web/ not found at", WEB, file=sys.stderr)
return 1
server = ThreadingHTTPServer(("127.0.0.1", PORT), partial(Handler))
print(f"Relay UI → http://127.0.0.1:{PORT}")
print(f"API proxy → {API}")
print("Ctrl+C to stop")
try:
server.serve_forever()
except KeyboardInterrupt:
print("\nbye")
return 0
if __name__ == "__main__":
raise SystemExit(main())