# -*- coding: utf-8 -*-
"""带 gzip 的静态文件服务，替代 python3 -m http.server（funnel 带宽有限，压缩后快 5-10 倍）。"""
import gzip, os
from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler

HERE = os.path.dirname(os.path.abspath(__file__))
COMPRESSIBLE = ('.html', '.js', '.css', '.json', '.svg', '.txt', '.md')
_cache = {}

class H(SimpleHTTPRequestHandler):
    protocol_version = 'HTTP/1.1'

    def __init__(self, *a, **kw):
        super().__init__(*a, directory=HERE, **kw)

    def do_GET(self):
        path = self.translate_path(self.path)
        if not self.path.endswith('/') and os.path.isfile(path) \
           and path.endswith(COMPRESSIBLE) \
           and 'gzip' in self.headers.get('Accept-Encoding', ''):
            mtime = os.path.getmtime(path)
            key = (path, mtime)
            if key not in _cache:
                with open(path, 'rb') as f:
                    _cache[key] = gzip.compress(f.read(), 6)
                if len(_cache) > 32:
                    _cache.clear()
            body = _cache[key]
            self.send_response(200)
            self.send_header('Content-Type', self.guess_type(path))
            self.send_header('Content-Encoding', 'gzip')
            self.send_header('Content-Length', str(len(body)))
            self.send_header('Cache-Control', 'no-cache')
            self.end_headers()
            self.wfile.write(body)
        else:
            super().do_GET()

    def log_message(self, *a):
        pass

if __name__ == '__main__':
    ThreadingHTTPServer(('0.0.0.0', 8899), H).serve_forever()
