#!/usr/bin/env python3
# 静态服务器：所有文本类型强制带 charset=utf-8，杜绝中文乱码
import http.server, socketserver, functools, os

class H(http.server.SimpleHTTPRequestHandler):
    def guess_type(self, path):
        t = super().guess_type(path)
        text_types = ('text/', 'application/javascript', 'application/json', 'application/xml')
        if t.startswith(text_types) or path.endswith(('.md', '.txt', '.json', '.html', '.js', '.csv')):
            base = t.split(';')[0]
            if base.startswith('application/octet-stream') or base == 'text/markdown' or base == 'text/plain':
                base = 'text/plain' if path.endswith(('.md', '.txt', '.csv')) else base
            return base + '; charset=utf-8'
        return t

os.chdir(os.path.dirname(os.path.abspath(__file__)))
socketserver.TCPServer.allow_reuse_address = True
with socketserver.ThreadingTCPServer(('0.0.0.0', 8898), H) as httpd:
    httpd.serve_forever()
