"""静态页面与资源文件服务。""" from __future__ import annotations from http import HTTPStatus from http.server import BaseHTTPRequestHandler from pathlib import Path from group_system.config import STATIC_DIR CONTENT_TYPES = { ".html": "text/html; charset=utf-8", ".htm": "text/html; charset=utf-8", ".css": "text/css; charset=utf-8", ".js": "text/javascript; charset=utf-8", ".mjs": "text/javascript; charset=utf-8", ".svg": "image/svg+xml", ".png": "image/png", } def send_text(handler: BaseHTTPRequestHandler, status: int, text: str) -> None: body = text.encode("utf-8") handler.send_response(status) handler.send_header("Content-Type", "text/plain; charset=utf-8") handler.send_header("Content-Length", str(len(body))) handler.end_headers() handler.wfile.write(body) def serve_file(handler: BaseHTTPRequestHandler, path: Path) -> None: path = path if path.is_absolute() else STATIC_DIR / path if not path.is_file(): send_text(handler, HTTPStatus.NOT_FOUND, "Not Found") return content_type = CONTENT_TYPES.get(path.suffix.lower(), "application/octet-stream") content = path.read_bytes() handler.send_response(HTTPStatus.OK) handler.send_header("Content-Type", content_type) handler.send_header("Content-Length", str(len(content))) handler.send_header("Cache-Control", "no-cache") handler.end_headers() handler.wfile.write(content)