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()