From 5d1f34524e228d221842b84490d6cbe01d0782cf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BC=A0=E5=AE=97=E5=B9=B3?= Date: Wed, 1 Jul 2026 17:35:14 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=20serve.py=20=E6=9C=AA?= =?UTF-8?q?=E5=A3=B0=E6=98=8E=20charset=20=E5=AF=BC=E8=87=B4=E4=B8=AD?= =?UTF-8?q?=E6=96=87=E4=B9=B1=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit http.server 的 guess_type() 从不附带 charset,直接导航到 .cpp/.md 等 文本文件时浏览器猜编码猜错,中文注释显示乱码。Content-Type 统一补 charset=utf-8。 --- docs/teaching/serve.py | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/docs/teaching/serve.py b/docs/teaching/serve.py index 3a61410..71b5a2e 100755 --- a/docs/teaching/serve.py +++ b/docs/teaching/serve.py @@ -32,6 +32,16 @@ class ReuseAddrTCPServer(socketserver.TCPServer): allow_reuse_address = True -with ReuseAddrTCPServer(("127.0.0.1", port), http.server.SimpleHTTPRequestHandler) as httpd: +class Utf8RequestHandler(http.server.SimpleHTTPRequestHandler): + # http.server 的 guess_type() 从不附带 charset——中文源码/文档被当成 + # 无编码信息的 text/plain 返回,浏览器直接导航时会猜错编码变成乱码。 + def guess_type(self, path): + ctype = super().guess_type(path) + if ctype.startswith("text/") and "charset=" not in ctype: + ctype += "; charset=utf-8" + return ctype + + +with ReuseAddrTCPServer(("127.0.0.1", port), Utf8RequestHandler) as httpd: print(f"Serving {repo_root} at http://localhost:{port}/docs/teaching/slides/index.html") httpd.serve_forever()