import http.server import socketserver import json import os import random import string from urllib.parse import urlparse, parse_qs PORT = 8000 # 生成唯一 ID def generate_unique_id(): return ''.join(random.choices(string.ascii_letters + string.digits, k=16)) # 确保静态文件目录存在 static_dir = os.path.join(os.path.dirname(__file__), '../frontend/public/static') if not os.path.exists(static_dir): os.makedirs(static_dir, exist_ok=True) class MyHTTPRequestHandler(http.server.SimpleHTTPRequestHandler): def do_POST(self): if self.path == '/api/html/generate': # 读取请求体 content_length = int(self.headers['Content-Length']) post_data = self.rfile.read(content_length) try: # 解析 JSON 数据 data = json.loads(post_data) html_content = data.get('html_content', '') if not html_content: self.send_response(400) self.send_header('Content-type', 'application/json') self.end_headers() self.wfile.write(json.dumps({'error': 'HTML 内容不能为空'}).encode('utf-8')) return # 生成唯一 ID unique_id = generate_unique_id() # 生成 HTML 文件路径 html_filename = f"{unique_id}.html" html_path = os.path.join(static_dir, html_filename) # 写入 HTML 内容 with open(html_path, 'w', encoding='utf-8') as f: f.write(html_content) # 生成完整链接 frontend_base_url = 'http://localhost:3000' html_url = f"{frontend_base_url}/static/{html_filename}" # 返回响应 self.send_response(201) self.send_header('Content-type', 'application/json') self.end_headers() response = { 'message': 'HTML 文件生成成功', 'unique_id': unique_id, 'url': html_url } self.wfile.write(json.dumps(response).encode('utf-8')) except Exception as e: self.send_response(500) self.send_header('Content-type', 'application/json') self.end_headers() self.wfile.write(json.dumps({'error': f'生成 HTML 文件失败: {str(e)}'}).encode('utf-8')) else: self.send_response(404) self.end_headers() def do_GET(self): if self.path == '/': # 健康检查 self.send_response(200) self.send_header('Content-type', 'application/json') self.end_headers() self.wfile.write(json.dumps({'message': 'HTML Generator API is running'}).encode('utf-8')) else: # 静态文件服务 super().do_GET() if __name__ == "__main__": with socketserver.TCPServer(("", PORT), MyHTTPRequestHandler) as httpd: print(f"服务器运行在 http://localhost:{PORT}") httpd.serve_forever()