2020
2121import contextlib
2222import logging
23- import mimetypes
2423import os
2524import re
2625import threading
2726
27+ import filetype
28+
2829try :
2930 from urllib import request as urllib_request
3031except ImportError :
@@ -71,20 +72,20 @@ def _serve_page(self, page_number):
7172
7273 def _serve_file (self , file_path ):
7374 """Serve a file from the HTML root directory."""
74- content_type , _ = mimetypes .guess_type (file_path )
75-
76- if content_type and (
77- content_type .startswith ("image/" )
78- or content_type .startswith ("application/" )
79- or content_type .startswith ("video/" )
80- or content_type .startswith ("audio/" )
81- ):
82- with open (file_path , "rb" ) as f :
83- return f .read ()
75+ with open (file_path , "rb" ) as f :
76+ content = f .read ()
77+
78+ kind = filetype .guess (content )
79+ if kind is not None :
80+ return content , kind .mime
81+
82+ # fallback for text files that filetype can't detect
83+ if file_path .endswith (".txt" ):
84+ return content , "text/plain"
85+ elif file_path .endswith (".json" ):
86+ return content , "application/json"
8487 else :
85- # text files
86- with open (file_path , encoding = "latin-1" ) as f :
87- return f .read ().encode ("utf-8" )
88+ return content , "text/html"
8889
8990 def _send_response (self , content_type = "text/html" ):
9091 """Send a response."""
@@ -102,8 +103,7 @@ def do_GET(self):
102103 self ._send_response ("text/html" )
103104 self .wfile .write (html )
104105 elif os .path .isfile (file_path ):
105- content_type , _ = mimetypes .guess_type (file_path )
106- content = self ._serve_file (file_path )
106+ content , content_type = self ._serve_file (file_path )
107107 self ._send_response (content_type )
108108 self .wfile .write (content )
109109 else :
0 commit comments