@@ -32,9 +32,16 @@ class BasicHTTPRequestHandler(SimpleHTTPRequestHandler):
3232
3333 def __init__ (self , * handler_args , ** handler_kwargs ) -> None :
3434 self .dir_listing = handler_kwargs .pop ('dir_listing' , False )
35+ self .enable_cors = handler_kwargs .pop ('enable_cors' , False )
3536 super ().__init__ (* handler_args , ** handler_kwargs )
3637 self .follow_symlinks = False
3738
39+ def end_headers (self ):
40+ """ Allow requests from any origin """
41+ if self .enable_cors :
42+ self .send_header ('Access-Control-Allow-Origin' , '*' )
43+ super ().end_headers ()
44+
3845 # https://en.wikipedia.org/wiki/List_of_Unicode_characters#Control_codes
3946 _control_char_table = str .maketrans ({c : fr'\x{ c :02x} ' for c in
4047 itertools .chain (range (0x20 ), range (0x7f , 0xa0 ))})
@@ -55,7 +62,7 @@ def list_directory(self, path: str | os.PathLike[str]) -> BytesIO | None:
5562 return super ().list_directory (path )
5663
5764
58- def basic_http_server (port : int , public_dir : Path , dir_listing : bool ) -> None :
65+ def basic_http_server (port : int , public_dir : Path , dir_listing : bool , cors : bool ) -> None :
5966 """ Starts a basic HTTP server """
6067 if not public_dir .exists () or not public_dir .is_dir ():
6168 logging .error ("Directory \" %s\" doesn't exist" , public_dir )
@@ -64,7 +71,8 @@ def basic_http_server(port: int, public_dir: Path, dir_listing: bool) -> None:
6471 logging .info ("Initializing Basic HTTP Server" )
6572 try :
6673 httpd = ThreadingBasicServer (("" , port ), partial (
67- BasicHTTPRequestHandler , directory = public_dir , dir_listing = dir_listing ))
74+ BasicHTTPRequestHandler , directory = public_dir ,
75+ dir_listing = dir_listing , enable_cors = cors ))
6876
6977 logging .info ("Available on port %s" , port )
7078 httpd .serve_forever ()
@@ -79,21 +87,23 @@ def parse_arguments() -> argparse.Namespace:
7987 formatter_class = CustomHelpFormatter
8088 )
8189
82- parser .add_argument ("-p" , "--port" , metavar = "" ,
90+ parser .add_argument ("-p" , "--port" ,
8391 default = 8080 , type = int ,
8492 help = "port to use [8080]" )
85- parser .add_argument ("-d" , "--dir" , metavar = "" ,
93+ parser .add_argument ("-d" , "--dir" , metavar = "PATH " ,
8694 default = Path (os .getcwd ()), type = Path ,
8795 help = "directory to serve [current directory]" )
8896 parser .add_argument ("-l" , "--listing" , action = "store_true" ,
8997 help = "enable directory listing" )
98+ parser .add_argument ("--cors" , action = "store_true" ,
99+ help = "enable CORS headers" )
90100 return parser .parse_args ()
91101
92102
93103if __name__ == "__main__" :
94104 args = parse_arguments ()
95105
96106 try :
97- basic_http_server (args .port , args .dir , args .listing )
107+ basic_http_server (args .port , args .dir , args .listing , args . cors )
98108 except KeyboardInterrupt :
99109 logging .info ("Basic HTTP Server stopped" )
0 commit comments