修复 serve.py 未声明 charset 导致中文乱码
http.server 的 guess_type() 从不附带 charset,直接导航到 .cpp/.md 等 文本文件时浏览器猜编码猜错,中文注释显示乱码。Content-Type 统一补 charset=utf-8。
This commit is contained in:
+11
-1
@@ -32,6 +32,16 @@ class ReuseAddrTCPServer(socketserver.TCPServer):
|
|||||||
allow_reuse_address = True
|
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")
|
print(f"Serving {repo_root} at http://localhost:{port}/docs/teaching/slides/index.html")
|
||||||
httpd.serve_forever()
|
httpd.serve_forever()
|
||||||
|
|||||||
Reference in New Issue
Block a user