about summary refs log tree commit diff
path: root/main.py
diff options
context:
space:
mode:
authorUltraQbik <no1skill@yandex.ru>2024-08-20 22:52:40 +0300
committerUltraQbik <no1skill@yandex.ru>2024-08-20 22:52:40 +0300
commite5df54da3967255edd3c945075389afbf81374e6 (patch)
tree9061c3c9300e64949deddd800b117da303a34251 /main.py
parentcb26d696dec66be1d163dd3a89ae0aa9bcb4cde9 (diff)
downloadhttpy-e5df54da3967255edd3c945075389afbf81374e6.tar.gz
httpy-e5df54da3967255edd3c945075389afbf81374e6.zip
Add gzip compression
Also changed 400 error to 404 error in get request handler
removed json import (might be temporary)
Diffstat (limited to 'main.py')
-rw-r--r--main.py20
1 files changed, 16 insertions, 4 deletions
diff --git a/main.py b/main.py
index 2cfceb8..491f85e 100644
--- a/main.py
+++ b/main.py
@@ -5,7 +5,6 @@ The mighty silly webserver written in python for no good reason
 
 import ssl
 import time
-import json
 import gzip
 import socket
 import asyncio
@@ -184,17 +183,25 @@ class HTTPServer:
         :param request: client's request
         """
 
+        # get available compression methods
+        compressions = [x.strip() for x in getattr(request, "Accept-Encoding", "").split(",")]
+
         # check if request path is in the PATH_MAP
         if request.path in PATH_MAP:
             # if it is -> return file from that path
             async with aiofiles.open(PATH_MAP[request.path]["path"], "rb") as f:
                 data = await f.read()
 
+            # add gzip compression header (if supported)
+            headers = {}
+            if "gzip" in compressions:
+                headers["Content-Encoding"] = "gzip"
+
             # send 200 response with the file to the client
-            HTTPServer._send(client, 200, data)
+            HTTPServer._send(client, 200, data, headers)
         else:
-            # send 400 response to the client
-            HTTPServer._send(client, 400)
+            # send 404 response to the client
+            HTTPServer._send(client, 404)
 
     @staticmethod
     def _send(client: socket.socket, response: int, data: bytes = None, headers: dict[str, str] = None):
@@ -214,6 +221,11 @@ class HTTPServer:
         if headers is None:
             headers = dict()
 
+        # check for 'content-encoding' header
+        if headers.get("Content-Encoding") == "gzip":
+            # if present -> compress data
+            data = gzip.compress(data)
+
         # format headers
         byte_header = bytearray()
         for key, value in headers.items():