Skip to content

Commit e4b2625

Browse files
committed
added cors to response
1 parent ba1e965 commit e4b2625

File tree

1 file changed

+8
-4
lines changed

1 file changed

+8
-4
lines changed

src/response.py

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,17 @@
11
import os
22

33
class Response:
4-
def __init__(self, writer):
4+
def __init__(self, writer, enable_cors=False):
55
self.writer = writer
6+
self.enable_cors = enable_cors
67

78
async def send_headers(self, status_code=200, content_type="text/html", content_length=None):
89
headers = f'HTTP/1.0 {status_code}\r\nContent-type: {content_type}\r\n'
10+
if self.enable_cors:
11+
# allow CORS
12+
headers += 'Access-Control-Allow-Origin: *\r\n'
13+
headers += 'Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS\r\n'
14+
headers += 'Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With\r\n'
915
if content_length is not None:
1016
headers += f'Content-Length: {content_length}\r\n'
1117
headers += '\r\n'
@@ -28,9 +34,9 @@ async def send_file(self, file_path, status_code=200, content_type="text/html"):
2834
try:
2935
file_size = os.stat(file_path)[6]
3036
await self.send_headers(status_code, content_type, content_length=file_size)
31-
3237
#chunk_size = 1024 # Adjust the chunk size as needed
3338
#chunk_size = 512 # Adjust the chunk size as needed
39+
#chunk_size = 256
3440
chunk_size = 256
3541
with open(file_path, "rb") as f:
3642
while True:
@@ -39,9 +45,7 @@ async def send_file(self, file_path, status_code=200, content_type="text/html"):
3945
break
4046
self.writer.write(chunk)
4147
await self.writer.drain()
42-
4348
await self.writer.wait_closed()
44-
4549
except Exception as e:
4650
print("Error sending file:", e)
4751
await self.send('', status_code=404)

0 commit comments

Comments
 (0)